import dateFns from 'date-fns';
import { convertStringToDate } from '../../services';
import { IInputDatePicker } from '../Datepicker/datepicker.interface';

/**
 * Transformar string ou object em valor de leitura componente
 * @param value
 */
export function transformerValue(
   value: string | IInputDatePicker | Date,
   options: { allDay?: boolean } = {},
): IInputDatePicker | null {
   if (!value) return null;

   if (typeof value === 'string') {
      const date = convertStringToDate(value);

      if (!date) {
         throw new Error('Data inválida');
      }

      return {
         day: dateFns.getDate(date),
         month: dateFns.getMonth(date) + 1,
         year: dateFns.getYear(date),
         date,
         dateYYYYMMDD: dateFns.format(date, 'yyyyMMdd'),
         dateYYYYMMDDhhiiss: dateFns.format(date, 'yyyyMMddHHmm00'),
         allDay: false,
         hour: dateFns.getHours(date),
         minutes: dateFns.getMinutes(date),
         isToday: dateFns.isToday(date),
      };
   }

   if (value instanceof Date) {
      return {
         day: dateFns.getDate(value),
         month: dateFns.getMonth(value) + 1,
         year: dateFns.getYear(value),
         date: value,
         dateYYYYMMDD: dateFns.format(value, 'yyyyMMdd'),
         dateYYYYMMDDhhiiss: options?.allDay
            ? dateFns.format(value, 'yyyyMMdd000000')
            : dateFns.format(value, 'yyyyMMddHHmm00'),
         allDay: !!options?.allDay,
         hour: options?.allDay ? 0 : dateFns.getHours(value),
         minutes: options?.allDay ? 0 : dateFns.getMinutes(value),
         isToday: dateFns.isToday(value),
      };
   }

   if (!value.date || !(value.date instanceof Date)) {
      throw new Error('Data inválida');
   }
   const date = value.date;

   return {
      day: dateFns.getDate(date),
      month: dateFns.getMonth(date) + 1,
      year: dateFns.getYear(date),
      date,
      dateYYYYMMDD: dateFns.format(date, 'yyyyMMdd'),
      dateYYYYMMDDhhiiss: options?.allDay
         ? dateFns.format(date, 'yyyyMMdd000000')
         : dateFns.format(date, 'yyyyMMddHHmm00'),
      allDay: options?.allDay || !!value.allDay,
      hour: options?.allDay ? 0 : dateFns.getHours(date),
      minutes: options?.allDay ? 0 : dateFns.getMinutes(date),
      isToday: dateFns.isToday(date),
   };
}

export function getDateValue(value: string | IInputDatePicker | Date): Date | null {
   if (!value) return null;

   if (typeof value === 'string') {
      const date = convertStringToDate(value);
      return date || null;
   }

   if (value instanceof Date) {
      return value;
   }

   if (!value.date || !(value.date! instanceof Date)) {
      throw new Error('Data inválida');
   }

   return value.date;
}
