"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SimpleScheduler = SimpleScheduler;
var _react = _interopRequireWildcard(require("react"));
var _faClock = require("@fortawesome/free-solid-svg-icons/faClock");
var _checkbox = require("../checkbox");
var _dropdownMenu = require("../dropdown-menu");
var _input = require("../input");
var _constants = require("./constants");
var _utils = require("./utils");
var _message = require("../message");
var _jsxRuntime = require("react/jsx-runtime");
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
const isInteger = /^\d+$/;
function MinutePicker({
  minute,
  onUpdateMinute,
  label,
  validationErrorText,
  isDisabled
}) {
  const [inputValue, setInputValue] = (0, _react.useState)(minute?.[0]);
  const [validityError, setValidityError] = (0, _react.useState)();
  (0, _react.useEffect)(function () {
    if (!validityError) {
      onUpdateMinute({
        minute: [Number(inputValue)]
      });
    } else {
      onUpdateMinute({
        minute
      }, validityError);
    }
  }, [inputValue]);
  function handleUpdate(e) {
    const {
      value
    } = e.target;
    const parsedValue = parseInt(value);
    const isValid = isInteger.test(value) && parsedValue >= 0 && parsedValue <= 59;
    setValidityError(isValid ? undefined : {
      type: _message.MESSAGE_TYPES.ERROR,
      value: validationErrorText,
      field: 'minute'
    });
    setInputValue(value);
  }
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_input.Input, {
    type: "number",
    min: 0,
    max: 59,
    step: 1,
    value: inputValue,
    label: label,
    "test-id": "minute-picker",
    id: "minutes-input",
    validity: validityError,
    onChange: handleUpdate,
    isDisabled: isDisabled
  });
}
function TimePicker({
  hour,
  minute,
  onUpdateTime,
  label,
  validationErrorText,
  isDisabled
}) {
  const paddedHour = hour?.toString().padStart(2, '0');
  const paddedMinute = minute?.toString().padStart(2, '0');
  const [inputValue, setInputValue] = (0, _react.useState)({
    hour: paddedHour,
    minute: paddedMinute
  });
  const [validityError, setValidityError] = (0, _react.useState)();
  (0, _react.useEffect)(() => {
    onUpdateTime({
      hour: [Number(inputValue.hour)],
      minute: [Number(inputValue.minute)]
    }, validityError);
  }, [inputValue]);
  function handleChange(e) {
    const {
      value
    } = e.target;
    const splitTime = value.split(':');
    const hourString = splitTime[0] || '';
    const minuteString = splitTime[1] || '';
    const isValid = isInteger.test(hourString) && isInteger.test(minuteString);
    setValidityError(isValid ? undefined : {
      type: _message.MESSAGE_TYPES.ERROR,
      value: validationErrorText,
      field: 'time'
    });
    setInputValue({
      hour: hourString,
      minute: minuteString
    });
  }
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_input.Input, {
    label: label,
    type: "time",
    "test-id": "time-picker",
    id: "time-input",
    value: `${inputValue.hour}:${inputValue.minute}`,
    validity: validityError,
    onChange: handleChange,
    step: 60,
    rightIcon: _faClock.faClock,
    isDisabled: isDisabled
  });
}
const DayOfWeekPicker = ({
  dayOfWeek = [],
  onUpdateDayOfWeek,
  daysOfWeek,
  label,
  isDisabled
}) => {
  const selectedDayOfWeek = dayOfWeek?.map(i => i) ?? [];
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
    className: "day-of-week-picker",
    "test-id": "day-of-week-picker",
    children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
      className: "day-of-week-label",
      children: label
    }), daysOfWeek.map(day => /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_checkbox.Checkbox, {
        id: `day-of-week-${day.index}`,
        testId: `day-of-week-checkbox-${day.index}`,
        className: "scheduler-checkbox",
        isChecked: selectedDayOfWeek.includes(day.index),
        labelText: day.label,
        onChange: e => {
          onUpdateDayOfWeek({
            dayOfWeek: e.target.checked ? [...dayOfWeek, day.index] : dayOfWeek?.filter(item => item !== day.index)
          });
        },
        isDisabled: isDisabled
      })
    }, `day-of-week-checkbox-${day.index}`))]
  });
};
const MonthPicker = ({
  month,
  onUpdateMonth,
  months,
  label,
  isDisabled
}) => /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
  className: "month-picker",
  "test-id": "month-picker",
  children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
    className: "month-checkbox-label",
    children: label
  }), Object.values(months).map(item => /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
    children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_checkbox.Checkbox, {
      id: `month-${item.index}`,
      testId: `month-checkbox-${item.index}`,
      className: "scheduler-checkbox",
      isChecked: month.includes(item.index),
      labelText: item.label,
      onChange: e => {
        onUpdateMonth({
          month: e.target.checked ?
          // Need to refactor the whole components to get ride of these 'as's
          [...month, item.index] : month.filter(m => m !== item.index)
        });
      },
      isDisabled: isDisabled
    })
  }, `month-checkbox-${item.index}`))]
});
function DayOfMonthPicker({
  dayOfMonth,
  onUpdateDayOfMonth,
  validateArrayOfRangedNumbersOrAll,
  label,
  isDisabled
}) {
  const [inputValue, setInputValue] = (0, _react.useState)(dayOfMonth?.join(','));
  const [validityError, setValidityError] = (0, _react.useState)();
  (0, _react.useEffect)(function () {
    if (!validityError) {
      onUpdateDayOfMonth({
        dayOfMonth: (0, _utils.stringToArrayOfNumbersOrAll)(inputValue)
      });
    } else {
      onUpdateDayOfMonth({
        dayOfMonth: (0, _utils.stringToArrayOfNumbersOrAll)(validityError?.validValues)
      }, validityError);
    }
  }, [inputValue]);
  function handleUpdate(value) {
    const values = value.split(',').filter(day => day);
    const updateValidity = validateArrayOfRangedNumbersOrAll({
      values,
      min: 1,
      max: 31,
      allowAll: false
    });
    setValidityError(updateValidity ? {
      ...updateValidity,
      field: 'dayOfMonth'
    } : undefined);
    setInputValue(value);
  }
  return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
    "test-id": "day-of-month-picker",
    children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_input.Input, {
      id: "dayOfMonth",
      "test-id": "day-of-month-input",
      label: label,
      name: "dayOfMonth",
      onChange: e => handleUpdate(e.target.value),
      value: inputValue,
      validity: validityError
      // show validity errors as they are typed without having to wait for the first blur
      ,
      touched: true,
      isDisabled: isDisabled
    })
  });
}
function SimpleScheduler({
  onUpdateSchedule,
  initialSchedule,
  frequencyOptions,
  validateArrayOfRangedNumbersOrAll,
  daysOfWeek,
  months,
  labelTexts,
  validationTexts,
  isDisabled
}) {
  const [schedule, setSchedule] = (0, _react.useState)(initialSchedule);
  const [frequency, setFrequency] = (0, _react.useState)((0, _utils.getFrequency)(initialSchedule));

  // TODO: Refactor with generic DropdownMenu
  function handleSelectFrequency(option) {
    setFrequency(option?.key);
    setSchedule(_constants.DEFAULT_SCHEDULES[option?.key]);
    onUpdateSchedule({
      newSchedule: _constants.DEFAULT_SCHEDULES[option?.key],
      errors: null
    });
  }
  function handleUpdateSchedule({
    minute,
    hour,
    dayOfMonth,
    month,
    dayOfWeek
  }, error = null) {
    const newSchedule = {
      minute: minute || schedule.minute,
      hour: hour || schedule.hour,
      dayOfMonth: dayOfMonth || schedule.dayOfMonth || error?.validValues,
      month: month || schedule.month,
      dayOfWeek: dayOfWeek || schedule.dayOfWeek
    };
    const errors = error ? [error] : null;
    setSchedule(newSchedule);
    onUpdateSchedule({
      newSchedule,
      errors
    });
  }
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
    className: "simple-scheduler-form",
    "test-id": "simple-scheduler",
    children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_dropdownMenu.DropdownMenu, {
      labelText: labelTexts.frequency,
      options: frequencyOptions,
      selectedKey: frequency,
      placement: "bottom",
      onSelect: handleSelectFrequency,
      selectbox: true,
      triggerTestId: "frequency-picker-trigger",
      triggerAriaLabelText: labelTexts.frequency,
      contentTestId: "frequency-picker-content",
      isDisabled: isDisabled
    }), frequency === _constants.FREQUENCIES.HOURLY && /*#__PURE__*/(0, _jsxRuntime.jsx)(MinutePicker, {
      minute: schedule.minute,
      onUpdateMinute: handleUpdateSchedule,
      label: labelTexts.minutesPastHour,
      validationErrorText: validationTexts.minuteError,
      isDisabled: isDisabled
    }, `minute-${frequency}`), (frequency === _constants.FREQUENCIES.DAILY || frequency === _constants.FREQUENCIES.WEEKLY || frequency === _constants.FREQUENCIES.MONTHLY || frequency === _constants.FREQUENCIES.QUARTERLY || frequency === _constants.FREQUENCIES.YEARLY) && /*#__PURE__*/(0, _jsxRuntime.jsx)(TimePicker, {
      hour: schedule?.hour?.[0],
      minute: schedule?.minute?.[0],
      onUpdateTime: ({
        minute,
        hour
      }, validityError) => {
        handleUpdateSchedule({
          minute,
          hour
        }, validityError);
      },
      label: labelTexts.time,
      validationErrorText: validationTexts.timeError,
      isDisabled: isDisabled
    }, `time-${frequency}`), frequency === _constants.FREQUENCIES.WEEKLY && /*#__PURE__*/(0, _jsxRuntime.jsx)(DayOfWeekPicker, {
      dayOfWeek: schedule.dayOfWeek,
      onUpdateDayOfWeek: ({
        dayOfWeek
      }) => {
        handleUpdateSchedule({
          dayOfWeek
        });
      },
      daysOfWeek: daysOfWeek,
      label: labelTexts.days,
      isDisabled: isDisabled
    }, `day-of-week-${frequency}`), (frequency === _constants.FREQUENCIES.MONTHLY || frequency === _constants.FREQUENCIES.QUARTERLY || frequency === _constants.FREQUENCIES.YEARLY) && /*#__PURE__*/(0, _jsxRuntime.jsx)(DayOfMonthPicker, {
      dayOfMonth: schedule.dayOfMonth,
      onUpdateDayOfMonth: handleUpdateSchedule,
      validateArrayOfRangedNumbersOrAll: validateArrayOfRangedNumbersOrAll,
      label: labelTexts.dayOfMonth,
      isDisabled: isDisabled
    }, `day-of-month-${frequency}`), frequency === _constants.FREQUENCIES.YEARLY && /*#__PURE__*/(0, _jsxRuntime.jsx)(MonthPicker, {
      month: schedule.month,
      onUpdateMonth: handleUpdateSchedule,
      months: months,
      label: labelTexts.months,
      isDisabled: isDisabled
    }, `month-${frequency}`)]
  });
}