import { sentenceCase } from 'change-case';
import {
  isInteger,
  isNil,
  merge,
  mergeWith
} from 'lodash';
import { titleCase } from 'title-case';

export function getPrettyShopifyObjectType(s:string): string {
  return titleCase(sentenceCase(s));
};

export function sleep(ms:number) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

/**
 * Great to use when using Array.prototype.filter since the type guard will remove
 * nil types from the array
 * @param value 
 * @returns 
 */
export function isPresent<TValue>(value: TValue | null | undefined): value is TValue {
  return !isNil(value);
}

export * from './dateUtil';

const combineArrays = (objValue:any, srcValue:any) => {
  if (Array.isArray(objValue)) {
    return objValue.concat(srcValue);
  }
};

export function mergeWithCombinedArrays(...params: Parameters<typeof merge>): ReturnType<typeof merge> {
  return mergeWith(...params, combineArrays);
}

const overwriteMergeArray = (objValue:any, srcValue:any) => {
  if (Array.isArray(objValue)) {
    return srcValue;
  }
};

export function mergeWithOverwrittenArrays(...params: Parameters<typeof merge>): ReturnType<typeof merge> {
  return mergeWith(...params, overwriteMergeArray);
}

export function range(num: number): number[] {
  return [
    ...Array(num)
      .keys()
  ];
}

export function getIntFromEnv(envVarName:string, defaultValue: number): number {
  const envVar = process.env[envVarName];

  if (isNil(envVar)) {
    return defaultValue;
  }

  const parsedInt = Number.parseInt(envVar);

  return isInteger(parsedInt) ? parsedInt : defaultValue;
}