"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.removeIrrelevantCharacters = exports.isInputInvalid = exports.getTimeSlots = exports.getTimeSlot = exports.getTimeFilter = exports.getSuggestedOption = exports.getFormattedDate = exports.getCustomTimeSlot = exports.getClosestTimeSlot = exports.getAutoFilledValue = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _designSystemsLocaleUtils = require("@wix/design-systems-locale-utils");
var _constants = require("./constants");
var _TimeInput = require("./TimeInput");
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2.default)(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var timeRegex = /([下上午오전후ÖS ]{0,})([0-2]?[0-9]{0,2})([:.h ]{0,})([0-5][0-9]{0,2})/;
var validationRegex = /^([下上午오전후ÖS ]{0,})(([0-1]?[0-9]|2[0-3])[^0-9]{0,}([0-5]([0-9]([^0-9]+)?)?)?)?$/;
var fullTimeNoDividerRegex = /([0-2]?[0-9])([0-5][0-9])/;
var _24hour2digitTimeRegex = [/^([0]?[3-9])([0-5])$/, /^([2])([4-5])$/, /^([0])()$/];
var _24hour3digitTimeRegex = [/^([0-1][0-9])([0-5])$/, /^([2][0-4])([0-5])$/];
var _24hourTimeRegex = _24hour2digitTimeRegex.concat(_24hour3digitTimeRegex);
var _12hour2digitTimeRegex = [/^([0]?[2-9])([0-5])$/, /^([0]?[1])([3-5])$/, /^([0])([0]?)$/];
var _12hour3digitTimeRegex = [/^([0][1-9])([0-5])$/, /^([1-9])([0-5][0-9])$/];
var _12hourTimeRegex = _12hour2digitTimeRegex.concat(_12hour3digitTimeRegex);
var getFormattedDate = _ref => {
  var {
    value,
    timeStyle,
    locale
  } = _ref;
  if (!value && value !== 0) {
    return '';
  }
  if (timeStyle === 'long') {
    return _designSystemsLocaleUtils.dateTimeFormat.getLongTime(locale, value);
  }
  return _designSystemsLocaleUtils.dateTimeFormat.getShortTime(locale, value);
};
exports.getFormattedDate = getFormattedDate;
var getTimeSlot = _ref2 => {
  var {
    value,
    timeStyle,
    locale
  } = _ref2;
  var formattedDate = getFormattedDate({
    value,
    timeStyle,
    locale
  });
  return {
    id: new Date(value).getTime(),
    value: formattedDate
  };
};
exports.getTimeSlot = getTimeSlot;
var getTimeSlots = _ref3 => {
  var {
    value = new Date(Date.now()),
    timeStyle,
    locale,
    step
  } = _ref3;
  var validatedStep = parseInt(step) ? parseInt(step) : _TimeInput.DEFAULT_STEP;
  var minuteMs = 60000;
  var stepMs = validatedStep > 60 ? 60 * minuteMs : validatedStep * minuteMs;
  var startOfTheDay = new Date(value).setHours(0, 0, 0, 0);
  var dayMs = 86400000;
  var amountOfTimeSlots = dayMs / stepMs;
  return new Array(amountOfTimeSlots).fill().map((_, i) => {
    var timeInMs = startOfTheDay + i * stepMs;
    return getTimeSlot({
      value: timeInMs,
      timeStyle,
      locale
    });
  });
};
exports.getTimeSlots = getTimeSlots;
var getClosestTimeSlot = _ref4 => {
  var {
    value = new Date(Date.now()),
    timeSlots
  } = _ref4;
  return timeSlots.find(option => option.id >= new Date(value).getTime());
};
exports.getClosestTimeSlot = getClosestTimeSlot;
var findTimeMatchAndAddDivider = (regexes, value) => {
  var matchedRegexIndex = regexes.findIndex(regex => regex.test(value));
  if (matchedRegexIndex !== -1) {
    return value.replace(regexes[matchedRegexIndex], addDivider);
  }
  return value;
};
var getCustomTimeSlot = _ref5 => {
  var {
    value,
    timeSlot,
    timeStyle,
    locale
  } = _ref5;
  var timeValue = value.replace(/[:.h ]{1,}/, ':').replace(/\.| /g, '').replace(/a\sm|PG|πμ|π|ص/i, 'AM').replace(/p\sm|PTG|μμ|μ|م/i, 'PM').replace(/(下午|下|오후|ÖS)(.*)/, (_, __, rest) => "".concat(rest, "PM")).replace(/(上午|上|오전|ÖÖ)(.*)/, (_, __, rest) => "".concat(rest, "AM")).replace(/[AP]$/i, match => "".concat(match, "M")).replace(/AM|PM/i, match => " ".concat(match));
  if (!timeValue && timeValue !== '0') {
    return;
  }
  if (_constants._24HOUR_TIME_FORMATS.includes(locale)) {
    timeValue = findTimeMatchAndAddDivider(_24hourTimeRegex, timeValue);
  }
  if (_constants._12HOUR_TIME_FORMATS.includes(locale)) {
    timeValue = findTimeMatchAndAddDivider(_12hourTimeRegex, timeValue);
  }
  if (fullTimeNoDividerRegex.test(timeValue)) {
    timeValue = timeValue.replace(fullTimeNoDividerRegex, addDivider);
  }
  if (/[0-2]?[0-9][:][0-9]$/.test(timeValue)) {
    timeValue = "".concat(timeValue, "0");
  }
  var timeSlotDate = _designSystemsLocaleUtils.dateTimeFormat.getShortDate('en', new Date(timeSlot));
  try {
    return getTimeSlot({
      value: new Date("".concat(timeSlotDate, " ").concat(timeValue)),
      timeStyle,
      locale
    });
  } catch (_unused) {
    return;
  }
};
exports.getCustomTimeSlot = getCustomTimeSlot;
var regexReplacer = (_, __, hours, divider, minutes) => {
  if (/^[1-9]$/.test(hours)) {
    return "0".concat(hours).concat(divider).concat(minutes);
  }
  return "".concat(hours).concat(divider).concat(minutes);
};
var addDivider = (_, hours, minutes) => {
  return "".concat(hours, ":").concat(minutes);
};
var normalizeTimeSlots = timeSlots => timeSlots.map(slot => _objectSpread(_objectSpread({}, slot), {}, {
  value: slot.value.replace(timeRegex, regexReplacer)
}));
var removeIrrelevantCharacters = input => input.replace(/[下上午오전후ÖS ]{0,}/, '');
exports.removeIrrelevantCharacters = removeIrrelevantCharacters;
var getAutoFilledValue = _ref6 => {
  var {
    inputValue,
    suggestedOption,
    locale
  } = _ref6;
  var value = removeIrrelevantCharacters(inputValue);
  if (suggestedOption.value.startsWith('0') && !value.startsWith('0')) {
    value = "0".concat(value);
  }
  var sliceTo = value.length;
  var valueMatchesPartial24hourTime = _constants._24HOUR_TIME_FORMATS.includes(locale) && _24hourTimeRegex.some(regex => regex.test(value));
  var valueMatchesPartial12hourTime = _constants._12HOUR_TIME_FORMATS.includes(locale) && _12hourTimeRegex.some(regex => regex.test(value));
  if (value.match(fullTimeNoDividerRegex) || valueMatchesPartial24hourTime || valueMatchesPartial12hourTime) {
    sliceTo = sliceTo + 1;
  }
  return suggestedOption.value.slice(sliceTo);
};
exports.getAutoFilledValue = getAutoFilledValue;
var findTimeMatch = (slot, value, locale) => slot.value.startsWith(value) || slot.value.startsWith("0".concat(value)) || slot.value.startsWith(value.replace(fullTimeNoDividerRegex, addDivider)) || slot.value.startsWith("0".concat(value).replace(fullTimeNoDividerRegex, addDivider)) || _constants._24HOUR_TIME_FORMATS.includes(locale) && (slot.value.startsWith(findTimeMatchAndAddDivider(_24hour2digitTimeRegex, value)) || slot.value.startsWith(findTimeMatchAndAddDivider(_24hour2digitTimeRegex, "0".concat(value))) || slot.value.startsWith(findTimeMatchAndAddDivider(_24hour3digitTimeRegex, value))) || _constants._12HOUR_TIME_FORMATS.includes(locale) && (slot.value.startsWith(findTimeMatchAndAddDivider(_12hour2digitTimeRegex, value)) || slot.value.startsWith(findTimeMatchAndAddDivider(_12hour2digitTimeRegex, "0".concat(value))) || slot.value.startsWith(findTimeMatchAndAddDivider(_12hour3digitTimeRegex, value)));
var getSuggestedOption = _ref7 => {
  var {
    inputValue,
    timeSlots,
    locale
  } = _ref7;
  var value = removeIrrelevantCharacters(inputValue);
  if (!value || value === '0') {
    return;
  }
  var currentTime = Date.now();
  var nextTimeSlotId = timeSlots.findIndex(time => time.id > currentTime);
  var highPriorityList = timeSlots.slice(nextTimeSlotId, timeSlots.length);
  var lowPriorityList = timeSlots.slice(0, nextTimeSlotId);
  var prioritizedList = [...highPriorityList, ...lowPriorityList];
  var normalizedTimeSlots = normalizeTimeSlots(prioritizedList);
  return normalizedTimeSlots.find(slot => findTimeMatch(slot, value, locale));
};
exports.getSuggestedOption = getSuggestedOption;
var isInputInvalid = inputValue => !validationRegex.test(inputValue);
exports.isInputInvalid = isInputInvalid;
var getTimeFilter = _ref8 => {
  var {
    excludePastTimes,
    filterTime = () => true
  } = _ref8;
  if (excludePastTimes) {
    var now = new Date();
    return time => time > now && filterTime(time);
  }
  return filterTime;
};
exports.getTimeFilter = getTimeFilter;
//# sourceMappingURL=TimeInputUtils.js.map