"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getFrequency = getFrequency;
exports.stringToArrayOfNumbersOrAll = void 0;
exports.useArrayOfRangedNumbersOrAllValidator = useArrayOfRangedNumbersOrAllValidator;
exports.useGetScheduleString = useGetScheduleString;
var _message = require("../message");
var _useTranslation = require("../hooks/use-translation");
var _constants = require("./constants");
const stringToArrayOfNumbersOrAll = value => String(value)?.split(',').filter(item => item === '*' || !Number.isNaN(parseInt(item))).map(item => item === '*' ? item : Number(item));
exports.stringToArrayOfNumbersOrAll = stringToArrayOfNumbersOrAll;
function useArrayOfRangedNumbersOrAllValidator() {
  const {
    t
  } = (0, _useTranslation.useTranslation)();
  return ({
    min,
    max,
    values,
    allowAll = true
  }) => {
    const validityMap = values?.map(item => {
      const parsedItem = Number(item);
      if (!item && item !== 0) {
        return true;
      }
      if (item === '*') {
        return !allowAll;
      }
      if (Number.isNaN(parsedItem) || !Number.isInteger(parsedItem)) {
        return true;
      }

      // is not within range
      if (parsedItem < Number(min) || parsedItem > Number(max)) {
        return true;
      }
      return false;
    });
    const validValues = values?.reduce((valid, current, index) => {
      let result = valid;
      if (!validityMap?.[index]) {
        result = valid.length === 0 ? current : `${result},${current}`;
      }
      return result;
    }, '');

    // report an error if any validation rule fails, or if the values array is empty (empty fields are not allowed)
    const validity = validityMap?.some(item => item) || values?.length === 0 ? {
      type: _message.MESSAGE_TYPES.ERROR,
      value: allowAll ? t('Value must be a comma-separated list of numbers between {{min}} and {{max}} or * for all', {
        min,
        max
      }) : t('Value must be a comma-separated list of numbers between {{min}} and {{max}}', {
        min,
        max
      }),
      validValues: validValues
    } : undefined;
    return validity;
  };
}
function useGetScheduleString() {
  const {
    t
  } = (0, _useTranslation.useTranslation)();
  const months = (0, _constants.useMonths)();
  const daysOfWeek = (0, _constants.useDaysOfWeek)();
  return (schedule, stringOptions = {}) => {
    const {
      complexScheduleString = t('Complex schedule'),
      timeStandardString = t('(UTC)')
    } = stringOptions;
    const scheduleStringTimeStandard = timeStandardString ? ` ${timeStandardString}` : '';
    switch (getFrequency(schedule)) {
      case _constants.FREQUENCIES.HOURLY:
        return schedule?.minute?.[0] === 1 ? t('Hourly at {{minutes}} minute past the hour', {
          minutes: schedule.minute[0].toString()
        }) : t('Hourly at {{minutes}} minutes past the hour', {
          minutes: schedule?.minute?.[0].toString()
        });
      case _constants.FREQUENCIES.DAILY:
        return `${t('Daily at {{hour}}:{{minutes}}', {
          hour: schedule?.hour?.[0].toString().padStart(2, '0'),
          minutes: schedule?.minute?.[0].toString().padStart(2, '0')
        })}${scheduleStringTimeStandard}`;
      case _constants.FREQUENCIES.WEEKLY:
        {
          const options = {
            hour: schedule?.hour?.[0].toString().padStart(2, '0'),
            minutes: schedule?.minute?.[0].toString().padStart(2, '0'),
            day: daysOfWeek.find(d => d.index === schedule?.dayOfWeek?.[0])?.label
          };
          const weeklyString = schedule?.dayOfWeek?.length === 1 ? t('Weekly on {{day}} at {{hour}}:{{minutes}}', {
            ...options
          }) : t('Weekly on multiple days at {{hour}}:{{minutes}}', {
            ...options
          });
          return `${weeklyString}${scheduleStringTimeStandard}`;
        }
      case _constants.FREQUENCIES.MONTHLY:
        {
          const options = {
            hour: schedule?.hour?.[0].toString().padStart(2, '0'),
            minutes: schedule?.minute?.[0].toString().padStart(2, '0'),
            day: schedule?.dayOfMonth?.[0],
            days: schedule?.dayOfMonth?.join(', ') // day 1, 2, 3
          };
          const monthlyString = schedule?.dayOfMonth?.length === 1 ? t('Monthly on day {{day}} at {{hour}}:{{minutes}}', {
            ...options
          }) : t('Monthly on days {{days}} at {{hour}}:{{minutes}}', {
            ...options
          });
          return `${monthlyString}${scheduleStringTimeStandard}`;
        }
      case _constants.FREQUENCIES.QUARTERLY:
        {
          const options = {
            hour: schedule?.hour?.[0].toString().padStart(2, '0'),
            minutes: schedule?.minute?.[0].toString().padStart(2, '0'),
            day: schedule?.dayOfMonth?.[0],
            days: schedule?.dayOfMonth?.join(', ') // day 1, 2, 3
          };
          const quarterlyString = schedule?.dayOfMonth?.length === 1 ? t('Quarterly on day {{day}} at {{hour}}:{{minutes}}', {
            ...options
          }) : t('Quarterly on days {{days}} at {{hour}}:{{minutes}}', {
            ...options
          });
          return `${quarterlyString}${scheduleStringTimeStandard}`;
        }
      case _constants.FREQUENCIES.YEARLY:
        {
          const options = {
            hour: schedule?.hour?.[0].toString().padStart(2, '0'),
            minutes: schedule?.minute?.[0].toString().padStart(2, '0'),
            day: schedule?.dayOfMonth?.[0],
            month: Object.values(months).find(m => m.index === schedule?.month?.[0])?.label
          };
          const yearlyString = Math.max(schedule?.month?.length ?? 0, schedule?.dayOfMonth?.length ?? 0) ? t('Yearly on {{month}} {{day}} at {{hour}}:{{minutes}}', {
            ...options
          }) : t('Yearly on multiple dates at {{hour}}:{{minutes}}', {
            ...options
          });
          return `${yearlyString}${scheduleStringTimeStandard}`;
        }
      default:
        return complexScheduleString;
    }
  };
}
function hasSameItems(arr1, arr2) {
  return arr1.length === arr2?.length && arr1.every(item1 => {
    return arr2.find(item2 => item2 === item1);
  });
}
function getFrequency({
  minute,
  hour,
  month,
  dayOfMonth,
  dayOfWeek
}) {
  if (minute?.length === 1 && !minute?.includes('*') && hour?.includes('*') && month?.includes('*') && dayOfMonth?.includes('*') && dayOfWeek?.includes('*')) {
    return _constants.FREQUENCIES.HOURLY;
  }
  if (minute?.length === 1 && !minute?.includes('*') && hour?.length === 1 && !hour?.includes('*') && month?.includes('*') && dayOfMonth?.includes('*') && dayOfWeek?.includes('*')) {
    return _constants.FREQUENCIES.DAILY;
  }
  if (minute?.length === 1 && !minute?.includes('*') && hour?.length === 1 && !hour?.includes('*') && month?.includes('*') && dayOfMonth?.includes('*') && !dayOfWeek?.includes('*') // multiple values are supported
  ) {
    return _constants.FREQUENCIES.WEEKLY;
  }
  if (minute?.length === 1 && !minute?.includes('*') && hour?.length === 1 && !hour?.includes('*') && month?.includes('*') && !dayOfMonth?.includes('*') &&
  // multiple values are supported
  dayOfWeek?.includes('*')) {
    return _constants.FREQUENCIES.MONTHLY;
  }
  if (minute?.length === 1 && !minute?.includes('*') && hour?.length === 1 && !hour?.includes('*') && hasSameItems([1, 4, 7, 10], month) && !dayOfMonth?.includes('*') && dayOfWeek?.includes('*')) {
    return _constants.FREQUENCIES.QUARTERLY;
  }
  if (minute?.length === 1 && !minute?.includes('*') && hour?.length === 1 && !hour?.includes('*') && !month?.includes('*') && !dayOfMonth?.includes('*') && dayOfWeek?.includes('*')) {
    return _constants.FREQUENCIES.YEARLY;
  }
}