'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _rollupPluginBabelHelpers = require('../../../_virtual/_rollupPluginBabelHelpers.js');
var React = require('react');
var datejs = require('../../../utils/datejs.js');
var dateHelper = require('../../DatePicker/utils/dateHelper.js');
var DateTimePicker_tokens = require('../DateTimePicker.tokens.js');
var getMaskedValue = require('../utils/getMaskedValue.js');
var getFormattedDateTime = require('../utils/getFormattedDateTime.js');
var normalizeDateTime = require('../utils/normalizeDateTime.js');
var constants = require('../../Calendar/utils/constants.js');

var useDateTimePicker = function useDateTimePicker(_ref) {
  var valueError = _ref.valueError,
    valueSuccess = _ref.valueSuccess,
    valueEdited = _ref.valueEdited,
    type = _ref.type,
    _ref$lang = _ref.lang,
    lang = _ref$lang === void 0 ? 'ru' : _ref$lang,
    disabled = _ref.disabled,
    readOnly = _ref.readOnly,
    outerValue = _ref.outerValue,
    defaultDate = _ref.defaultDate,
    maskWithFormat = _ref.maskWithFormat,
    _ref$dateFormat = _ref.dateFormat,
    dateFormat = _ref$dateFormat === void 0 ? 'DD.MM.YYYY' : _ref$dateFormat,
    _ref$timeFormat = _ref.timeFormat,
    timeFormat = _ref$timeFormat === void 0 ? 'HH:mm:ss' : _ref$timeFormat,
    _ref$dateTimeSeparato = _ref.dateTimeSeparator,
    dateTimeSeparator = _ref$dateTimeSeparato === void 0 ? ' ' : _ref$dateTimeSeparato,
    inputRef = _ref.inputRef,
    min = _ref.min,
    max = _ref.max,
    includeEdgeDates = _ref.includeEdgeDates,
    dateOnTimeSelectOnly = _ref.dateOnTimeSelectOnly,
    preserveInvalidOnBlur = _ref.preserveInvalidOnBlur,
    onChangeValue = _ref.onChangeValue,
    onCommitDate = _ref.onCommitDate,
    onBlur = _ref.onBlur;
  var errorClass = valueError ? DateTimePicker_tokens.classes.error : undefined;
  var successClass = valueSuccess ? DateTimePicker_tokens.classes.success : undefined;
  var editedClass = valueEdited ? DateTimePicker_tokens.classes.edited : undefined;
  var dateFormatDelimiter = React.useMemo(function () {
    return dateHelper.getDateFormatDelimiter(dateFormat);
  }, [dateFormat]);
  var timeFormatDelimiter = React.useMemo(function () {
    return dateHelper.getDateFormatDelimiter(timeFormat);
  }, [timeFormat]);
  var delimiters = [dateFormatDelimiter, timeFormatDelimiter, dateTimeSeparator];
  var format = dateFormat + dateTimeSeparator + timeFormat;
  var timeColumnsCount = (timeFormat === null || timeFormat === void 0 ? void 0 : timeFormat.split(timeFormatDelimiter).length) || 2;
  var _useState = React.useState(defaultDate || ''),
    _useState2 = _rollupPluginBabelHelpers.slicedToArray(_useState, 2),
    innerDate = _useState2[0],
    setInnerDate = _useState2[1];
  var dateVisibleValue = outerValue !== null && outerValue !== void 0 ? outerValue : innerDate;
  var initialValues = getFormattedDateTime.getFormattedDateTime({
    value: dateVisibleValue,
    lang: lang,
    format: format,
    includeEdgeDates: includeEdgeDates,
    min: min,
    max: max,
    dateFormat: dateFormat,
    timeFormat: timeFormat
  });
  var _useState3 = React.useState({
      input: initialValues.formattedDate,
      calendar: initialValues.dateValue,
      time: initialValues.timeValue
    }),
    _useState4 = _rollupPluginBabelHelpers.slicedToArray(_useState3, 2),
    correctDates = _useState4[0],
    setCorrectDates = _useState4[1];
  var calendarGridValue = initialValues.dateValue;
  var timeGridValue = initialValues.timeValue;
  datejs.customDayjs.locale(lang);
  var timeVisibleValue = timeGridValue ? datejs.customDayjs(timeGridValue).format(timeFormat) : '';
  var inputValue = initialValues.formattedDate;
  var getQuarterInfo = function getQuarterInfo(originalDate) {
    if (type !== 'Quarters' || !originalDate) {
      return;
    }
    var endQuarter = new Date(originalDate);
    endQuarter.setMonth(originalDate.getMonth() + 3);
    endQuarter.setDate(0);
    datejs.customDayjs.locale(lang);
    var quarterIndex = datejs.customDayjs(originalDate).quarter() - 1;
    return {
      name: constants.QUARTER_NAMES[quarterIndex],
      fullValue: [originalDate, endQuarter]
    };
  };
  var isDateEqualEdge = function isDateEqualEdge(dateEdge) {
    if (!dateEdge || !correctDates.calendar) {
      return false;
    }
    var normalizedEdgeDate = datejs.customDayjs(dateEdge).startOf('day');
    var normalizedCurrentDate = datejs.customDayjs(correctDates.calendar).startOf('day');
    return normalizedCurrentDate.isSame(normalizedEdgeDate);
  };
  var getFormattedCorrectInput = function getFormattedCorrectInput(_ref2) {
    var originalDate = _ref2.originalDate,
      formattedDate = _ref2.formattedDate,
      dateValue = _ref2.dateValue,
      timeValue = _ref2.timeValue;
    if (originalDate || formattedDate === '') {
      return {
        input: formattedDate
      };
    }
    if (dateValue && timeValue) {
      return {
        input: formattedDate
      };
    }
    if (dateValue && !timeValue) {
      return {
        input: formattedDate.slice(0, dateFormat === null || dateFormat === void 0 ? void 0 : dateFormat.length)
      };
    }
    return {
      input: ''
    };
  };
  var handleChangeValue = function handleChangeValue(event) {
    if (disabled || readOnly) {
      return;
    }
    var _event$target = event.target,
      value = _event$target.value,
      selectionStart = _event$target.selectionStart;
    var _ref3 = maskWithFormat ? getMaskedValue.getMaskedValue({
        value: value,
        format: format,
        delimiters: delimiters,
        prevValue: inputValue,
        selectionStart: selectionStart
      }) : {
        formattedValue: value,
        selectionStart: selectionStart
      },
      formattedValue = _ref3.formattedValue,
      newSelectionStart = _ref3.selectionStart;
    var _getFormattedDateTime = getFormattedDateTime.getFormattedDateTime({
        value: formattedValue,
        lang: lang,
        format: format,
        dateFormat: dateFormat,
        timeFormat: timeFormat,
        includeEdgeDates: includeEdgeDates,
        min: min,
        max: max
      }),
      formattedDate = _getFormattedDateTime.formattedDate,
      isoDate = _getFormattedDateTime.isoDate,
      originalDate = _getFormattedDateTime.originalDate,
      dateValue = _getFormattedDateTime.dateValue,
      timeValue = _getFormattedDateTime.timeValue;
    var _getFormattedCorrectI = getFormattedCorrectInput({
        originalDate: originalDate,
        formattedDate: formattedDate,
        dateValue: dateValue,
        timeValue: timeValue
      }),
      inputCorrectValue = _getFormattedCorrectI.input;
    setCorrectDates(function (prevCorrectDates) {
      return _rollupPluginBabelHelpers.objectSpread2(_rollupPluginBabelHelpers.objectSpread2({}, prevCorrectDates), {}, {
        input: inputCorrectValue,
        calendar: inputCorrectValue ? dateValue || prevCorrectDates.calendar : undefined,
        time: inputCorrectValue ? timeValue || prevCorrectDates.time : undefined
      });
    });
    setInnerDate(formattedDate);
    if (originalDate) {
      var quarterInfo = getQuarterInfo(originalDate);
      if (onCommitDate) {
        onCommitDate(formattedDate, {
          quarterInfo: quarterInfo,
          originalDate: originalDate,
          isoDate: isoDate
        });
      }
    }
    if (onChangeValue) {
      onChangeValue(event, formattedDate, {
        originalDate: originalDate,
        isoDate: isoDate
      });
    }
    requestAnimationFrame(function () {
      if (inputRef.current) {
        inputRef.current.setSelectionRange(newSelectionStart, newSelectionStart);
      }
    });
  };
  var handleSearch = function handleSearch(date) {
    if (disabled || readOnly) {
      return;
    }
    if (!date) {
      if (onCommitDate) {
        onCommitDate('', {
          quarterInfo: undefined,
          originalDate: undefined,
          isoDate: ''
        });
      }
      return;
    }
    var _getFormattedDateTime2 = getFormattedDateTime.getFormattedDateTime({
        value: date,
        lang: lang,
        format: format,
        dateFormat: dateFormat,
        timeFormat: timeFormat,
        includeEdgeDates: includeEdgeDates,
        min: min,
        max: max
      }),
      formattedDate = _getFormattedDateTime2.formattedDate,
      isoDate = _getFormattedDateTime2.isoDate,
      originalDate = _getFormattedDateTime2.originalDate;
    var quarterInfo = getQuarterInfo(originalDate);
    if (onCommitDate) {
      onCommitDate(formattedDate, {
        quarterInfo: quarterInfo,
        originalDate: originalDate,
        isoDate: isoDate
      });
    }
  };
  var handleCalendarPick = function handleCalendarPick(date, quarterInfo) {
    if (disabled || readOnly) {
      return;
    }
    if (!date) {
      return;
    }
    datejs.customDayjs.locale(lang);
    var rawDate = datejs.customDayjs(date);
    if (correctDates.time) {
      var correctTimeDate = datejs.customDayjs(correctDates.time);
      var correctHours = correctTimeDate.get('hours');
      var correctMinutes = correctTimeDate.get('minutes');
      var correctSeconds = correctTimeDate.get('seconds');
      rawDate = rawDate.set('hours', correctHours).set('minutes', correctMinutes).set('seconds', correctSeconds);
    }
    var _normalizeDateTime = normalizeDateTime.normalizeDateTime({
        originalDate: rawDate.toDate(),
        lang: lang,
        format: format,
        includeEdgeDates: includeEdgeDates,
        min: min,
        max: max
      }),
      normalizedDate = _normalizeDateTime.normalizedDate,
      formattedNormalizedDate = _normalizeDateTime.formattedNormalizedDate;
    var isoDate = normalizedDate.toISOString();
    setCorrectDates(function (prevCorrectDates) {
      return _rollupPluginBabelHelpers.objectSpread2(_rollupPluginBabelHelpers.objectSpread2({}, prevCorrectDates), {}, {
        input: formattedNormalizedDate,
        calendar: normalizedDate,
        time: normalizedDate
      });
    });
    setInnerDate(formattedNormalizedDate);
    if (onCommitDate) {
      onCommitDate(formattedNormalizedDate, {
        quarterInfo: quarterInfo,
        originalDate: normalizedDate,
        isoDate: isoDate
      });
    }
    if (onChangeValue) {
      onChangeValue(null, formattedNormalizedDate, {
        originalDate: normalizedDate,
        isoDate: isoDate
      });
    }
  };
  var handleTimePick = function handleTimePick(time) {
    if (disabled || readOnly) {
      return;
    }
    if (!(time !== null && time !== void 0 && time.value)) {
      return;
    }
    datejs.customDayjs.locale(lang);
    var rawDate;
    if (!correctDates.calendar) {
      if (dateOnTimeSelectOnly) {
        rawDate = datejs.customDayjs(dateOnTimeSelectOnly);
      } else {
        rawDate = datejs.customDayjs();
      }
    } else {
      rawDate = datejs.customDayjs(correctDates.calendar);
    }
    var timeValues = time.timeValues;
    rawDate = rawDate.set('hours', timeValues.hour || 0).set('minutes', timeValues.minute || 0).set('seconds', timeValues.second || 0);
    var _normalizeDateTime2 = normalizeDateTime.normalizeDateTime({
        originalDate: rawDate.toDate(),
        lang: lang,
        format: format,
        includeEdgeDates: includeEdgeDates,
        min: min,
        max: max
      }),
      normalizedDate = _normalizeDateTime2.normalizedDate,
      formattedNormalizedDate = _normalizeDateTime2.formattedNormalizedDate;
    var isoDate = normalizedDate.toISOString();
    var quarterInfo = getQuarterInfo(normalizedDate);
    setCorrectDates(function (prevCorrectDates) {
      return _rollupPluginBabelHelpers.objectSpread2(_rollupPluginBabelHelpers.objectSpread2({}, prevCorrectDates), {}, {
        input: formattedNormalizedDate,
        calendar: normalizedDate,
        time: normalizedDate
      });
    });
    setInnerDate(formattedNormalizedDate);
    if (onCommitDate) {
      onCommitDate(formattedNormalizedDate, {
        quarterInfo: quarterInfo,
        originalDate: normalizedDate,
        isoDate: isoDate
      });
    }
    if (onChangeValue) {
      onChangeValue(null, formattedNormalizedDate, {
        originalDate: normalizedDate,
        isoDate: isoDate
      });
    }
  };
  var updateExternalDate = function updateExternalDate(externalDate) {
    var _getFormattedDateTime3 = getFormattedDateTime.getFormattedDateTime({
        value: externalDate,
        lang: lang,
        format: format,
        dateFormat: dateFormat,
        timeFormat: timeFormat,
        includeEdgeDates: includeEdgeDates,
        min: min,
        max: max
      }),
      formattedDate = _getFormattedDateTime3.formattedDate,
      originalDate = _getFormattedDateTime3.originalDate,
      dateValue = _getFormattedDateTime3.dateValue,
      timeValue = _getFormattedDateTime3.timeValue;
    var _getFormattedCorrectI2 = getFormattedCorrectInput({
        originalDate: originalDate,
        formattedDate: formattedDate,
        dateValue: dateValue,
        timeValue: timeValue
      }),
      inputCorrectValue = _getFormattedCorrectI2.input;
    setCorrectDates(function (prevCorrectDates) {
      return _rollupPluginBabelHelpers.objectSpread2(_rollupPluginBabelHelpers.objectSpread2({}, prevCorrectDates), {}, {
        input: inputCorrectValue,
        calendar: inputCorrectValue ? dateValue || prevCorrectDates.calendar : undefined,
        time: inputCorrectValue ? timeValue || prevCorrectDates.time : undefined
      });
    });
    setInnerDate(formattedDate);
  };
  var handleBlur = function handleBlur(event) {
    if (!preserveInvalidOnBlur) {
      datejs.customDayjs.locale(lang);
      var originalDate = correctDates.calendar;
      if (!originalDate) {
        if (onChangeValue) {
          onChangeValue(event, correctDates.input, {
            originalDate: undefined,
            isoDate: ''
          });
        }
        if (onCommitDate) {
          onCommitDate(correctDates.input, {
            quarterInfo: undefined,
            originalDate: undefined,
            isoDate: ''
          });
        }
        return;
      }
      if (correctDates.time) {
        originalDate.setHours(correctDates.time.getHours(), correctDates.time.getMinutes(), correctDates.time.getSeconds());
      }
      setInnerDate(originalDate);
      if (!timeGridValue) {
        if (correctDates.calendar) {
          setInnerDate(correctDates.calendar);
        }
      }
      if (onChangeValue) {
        onChangeValue(event, correctDates.input, {
          originalDate: originalDate,
          isoDate: originalDate.toISOString()
        });
      }
      if (onCommitDate) {
        var quarterInfo = getQuarterInfo(originalDate);
        onCommitDate(correctDates.input, {
          quarterInfo: quarterInfo,
          originalDate: originalDate,
          isoDate: originalDate.toISOString()
        });
      }
    }
    if (onBlur) {
      onBlur(event);
    }
  };
  React.useLayoutEffect(function () {
    if (outerValue !== undefined && !outerValue) {
      setInnerDate('');
      setCorrectDates({
        input: '',
        calendar: undefined,
        time: undefined
      });
    }
  }, [outerValue]);
  return {
    format: format,
    dateVisibleValue: dateVisibleValue,
    calendarGridValue: calendarGridValue,
    inputValue: inputValue,
    timeVisibleValue: timeVisibleValue,
    timeColumnsCount: timeColumnsCount,
    errorClass: errorClass,
    successClass: successClass,
    editedClass: editedClass,
    handleChangeValue: handleChangeValue,
    handleSearch: handleSearch,
    handleCalendarPick: handleCalendarPick,
    handleTimePick: handleTimePick,
    handleBlur: handleBlur,
    updateExternalDate: updateExternalDate,
    getQuarterInfo: getQuarterInfo,
    isDateEqualEdge: isDateEqualEdge
  };
};

exports.useDateTimePicker = useDateTimePicker;
