/**
 * Copyright 2024 Phenix Real Time Solutions, Inc. Confidential and Proprietary. All Rights Reserved.
 */
import moment, {DurationInputArg1, unitOfTime} from 'moment';
import PlatformDetectionService from 'services/platformDetection.service';

export const truncateWord = (word = '', length = 30): string => {
  if (word.length >= length) {
    return `${word.substring(0, length)}...`;
  }

  return word;
};

export const isEqual = (a: unknown, b: unknown): boolean => {
  if (typeof a === typeof b) {
    if (typeof a === 'object') {
      return JSON.stringify(a) === JSON.stringify(b);
    }

    return a === b;
  }

  return false;
};

export const splitWord = (string = ' ', seperator = ' '): string => {
  return string.split(/(?=[A-Z])/).join(seperator);
};

export const mergeSimilarCSVFiles = (formerCSV: string, latterCSV: string): string => {
  const formerCsvArray = formerCSV.split('\n').filter(line => line.trim() !== '');
  const latterCsvArray = latterCSV.split('\n').filter(line => line.trim() !== '');

  if (latterCsvArray.length > 1) {
    return `${formerCsvArray.join('\n')}\n${latterCsvArray.splice(1).join('\n')}`;
  }

  return formerCSV;
};

export const chunk = <T>(array: T[], size: number = 1): T[][] => {
  const arrayChunks: T[][] = [];

  for (let i = 0; i < array.length; i += size) {
    const arrayChunk = array.slice(i, i + size);

    arrayChunks.push(arrayChunk);
  }

  return arrayChunks;
};

export const getRangeByInterval = (start: Date, end: Date, intervalAmount: DurationInputArg1 = 24, intervalUnits: unitOfTime.DurationConstructor = 'hours') => {
  const datesArray = [];
  let currentDate = moment.utc(start);
  const stopDate = moment.utc(end);

  while (currentDate.isSameOrBefore(stopDate)) {
    datesArray.push(currentDate.toISOString());
    currentDate = currentDate.add(intervalAmount, intervalUnits);
  }

  return datesArray.reverse();
};

export const getBrowserLimits = (): IBrowserLimits => browserLimits[PlatformDetectionService.browserName.toLowerCase()];

export const getMaxByPropertyName = (array: Record<string, number | string | boolean>[], propertyName: string): number => {
  let length = array.length;
  let max = -Infinity;

  while (length--) {
    const element = parseFloat(array[length][propertyName] as string);

    if (isFinite(element) && element > max) {
      max = element;
    }
  }

  return max;
};
