import { format, formatISO } from 'date-fns';
import { DATE_TIME_FORMAT } from '../constants/define';
import { isEqual, isPlainObject, snakeCase } from 'lodash';

export const getPathWithParams = (path = '', params = {}) => {
  Object.keys(params).forEach((p) => {
    const searchStrParam = `/:${p}`;
    path = path.replace(searchStrParam, `/${params[p]}`);
  });
  return path;
};

export const safeJsonParse = (str) => {
  try {
    return JSON.parse(str) === '' ? [] : JSON.parse(str);
  } catch {
    return [];
  }
};

export const formatDate = (date, formatStr = 'yyyy-MM-dd') => {
  if (typeof date === 'string') {
    date = formatISO(new Date(date), { representation: 'date' });
  }
  return format(date, formatStr);
};

export const convertDateToString = (date, formatStr = DATE_TIME_FORMAT.SHORT_DATE_EXPORT) => {
  if (!date) return '';
  return format(date, formatStr);
};

export const convertCamelCaseToSnakeCase = (str) => {
  return snakeCase(str);
};

export const convertObjectToJsonString = (obj) => {
  if (!obj) return;
  return JSON.stringify(obj);
};

export const getDiff = (values, initialValues) => {
  const diff = {};
  Object.keys(values).forEach((key) => {
    if (!isEqual(values[key], initialValues[key])) {
      diff[key] = values[key];
    }
  });
  return diff;
};
