import { i18n } from '@plugins/i18n';
import { StringRuleFunctionType } from './types/main';
import {
  convertDateFormat,
  convertDateFromBackendFormat,
} from '@utils/format-date';
import { DateFormat } from '@constants/utils/format-date';

export function dateIsMoreThanCurrentRule(
  dateMask = DateFormat.date,
  includes = true
): StringRuleFunctionType {
  return (val: string) => {
    return (
      (includes
        ? convertDateFormat(String(val), dateMask, DateFormat.yearMonthDay) >=
          convertDateFromBackendFormat(new Date(), DateFormat.yearMonthDay)
        : convertDateFormat(String(val), dateMask, DateFormat.yearMonthDay) >
          convertDateFromBackendFormat(new Date(), DateFormat.yearMonthDay)) ||
      String(
        i18n.t(
          `validation.dates.dateIsMoreThanCurrent${
            includes ? 'Includes' : 'Excludes'
          }`
        )
      )
    );
  };
}

export function dateIsLowerThanCurrentRule(
  dateMask = DateFormat.date,
  includes = true
): StringRuleFunctionType {
  return (val: string) => {
    return (
      (includes
        ? convertDateFormat(String(val), dateMask, DateFormat.yearMonthDay) <=
          convertDateFromBackendFormat(new Date(), DateFormat.yearMonthDay)
        : convertDateFormat(String(val), dateMask, DateFormat.yearMonthDay) <
          convertDateFromBackendFormat(new Date(), DateFormat.yearMonthDay)) ||
      String(
        i18n.t(
          `validation.dates.dateIsLowerThanCurrent${
            includes ? 'Includes' : 'Excludes'
          }`
        )
      )
    );
  };
}

export const getCurrentDate = (): string => {
  const [
    currentYear,
    currentMonth,
    currentDay,
  ] = new Date().toISOString().split('T')[0].split('-');
  return [currentYear, currentMonth, currentDay].join('-');
};

export const formatDate = (date: string | moment.Moment): string => {
  const dt = `${date}`.split('T')?.[0] ?? '';
  const [day, month, year] = dt.split('.');
  if (dt?.length === 10) return `${year}-${month}-${day}`;
  return date as string;
};

export const unformatDate = (date: string | moment.Moment): string => {
  const formattedDate =
    (date as moment.Moment)?.format?.('YYYY-MM-DD') ??
    `${date}`.split('T')?.[0] ??
    '';
  if (formattedDate?.length === 10) {
    return formattedDate.split('.').reverse().join('-');
  }
  return date as string;
};
