"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "useDateTimePicker", {
    enumerable: true,
    get: function() {
        return useDateTimePicker;
    }
});
var _react = require("react");
var _datejs = require("../../../utils/datejs");
var _utils = require("../../Calendar/utils");
var _dateHelper = require("../../DatePicker/utils/dateHelper");
var _DateTimePickertokens = require("../DateTimePicker.tokens");
var _getMaskedValue = require("../utils/getMaskedValue");
var _utils1 = require("../utils");
function _array_like_to_array(arr, len) {
    if (len == null || len > arr.length) len = arr.length;
    for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
    return arr2;
}
function _array_with_holes(arr) {
    if (Array.isArray(arr)) return arr;
}
function _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
function _iterable_to_array_limit(arr, i) {
    var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
    if (_i == null) return;
    var _arr = [];
    var _n = true;
    var _d = false;
    var _s, _e;
    try {
        for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
            _arr.push(_s.value);
            if (i && _arr.length === i) break;
        }
    } catch (err) {
        _d = true;
        _e = err;
    } finally{
        try {
            if (!_n && _i["return"] != null) _i["return"]();
        } finally{
            if (_d) throw _e;
        }
    }
    return _arr;
}
function _non_iterable_rest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _object_spread(target) {
    for(var i = 1; i < arguments.length; i++){
        var source = arguments[i] != null ? arguments[i] : {};
        var ownKeys = Object.keys(source);
        if (typeof Object.getOwnPropertySymbols === "function") {
            ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
                return Object.getOwnPropertyDescriptor(source, sym).enumerable;
            }));
        }
        ownKeys.forEach(function(key) {
            _define_property(target, key, source[key]);
        });
    }
    return target;
}
function ownKeys(object, enumerableOnly) {
    var keys = Object.keys(object);
    if (Object.getOwnPropertySymbols) {
        var symbols = Object.getOwnPropertySymbols(object);
        if (enumerableOnly) {
            symbols = symbols.filter(function(sym) {
                return Object.getOwnPropertyDescriptor(object, sym).enumerable;
            });
        }
        keys.push.apply(keys, symbols);
    }
    return keys;
}
function _object_spread_props(target, source) {
    source = source != null ? source : {};
    if (Object.getOwnPropertyDescriptors) {
        Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
    } else {
        ownKeys(Object(source)).forEach(function(key) {
            Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
        });
    }
    return target;
}
function _sliced_to_array(arr, i) {
    return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
}
function _unsupported_iterable_to_array(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _array_like_to_array(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor) n = o.constructor.name;
    if (n === "Map" || n === "Set") return Array.from(n);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
var useDateTimePicker = function useDateTimePicker(param) {
    var valueError = param.valueError, valueSuccess = param.valueSuccess, type = param.type, _param_lang = param.lang, lang = _param_lang === void 0 ? 'ru' : _param_lang, disabled = param.disabled, readOnly = param.readOnly, outerValue = param.outerValue, defaultDate = param.defaultDate, maskWithFormat = param.maskWithFormat, _param_dateFormat = param.dateFormat, dateFormat = _param_dateFormat === void 0 ? 'DD.MM.YYYY' : _param_dateFormat, _param_timeFormat = param.timeFormat, timeFormat = _param_timeFormat === void 0 ? 'HH:mm:ss' : _param_timeFormat, _param_dateTimeSeparator = param.dateTimeSeparator, dateTimeSeparator = _param_dateTimeSeparator === void 0 ? ' ' : _param_dateTimeSeparator, inputRef = param.inputRef, min = param.min, max = param.max, includeEdgeDates = param.includeEdgeDates, dateOnTimeSelectOnly = param.dateOnTimeSelectOnly, preserveInvalidOnBlur = param.preserveInvalidOnBlur, onChangeValue = param.onChangeValue, onCommitDate = param.onCommitDate, onBlur = param.onBlur;
    var errorClass = valueError ? _DateTimePickertokens.classes.error : undefined;
    var successClass = valueSuccess ? _DateTimePickertokens.classes.success : undefined;
    var dateFormatDelimiter = (0, _react.useMemo)(function() {
        return (0, _dateHelper.getDateFormatDelimiter)(dateFormat);
    }, [
        dateFormat
    ]);
    var timeFormatDelimiter = (0, _react.useMemo)(function() {
        return (0, _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 = _sliced_to_array((0, _react.useState)(defaultDate || ''), 2), innerDate = _useState[0], setInnerDate = _useState[1];
    var dateVisibleValue = outerValue !== null && outerValue !== void 0 ? outerValue : innerDate;
    var initialValues = (0, _utils1.getFormattedDateTime)({
        value: dateVisibleValue,
        lang: lang,
        format: format,
        includeEdgeDates: includeEdgeDates,
        min: min,
        max: max,
        dateFormat: dateFormat,
        timeFormat: timeFormat
    });
    var _useState1 = _sliced_to_array((0, _react.useState)({
        input: initialValues.formattedDate,
        calendar: initialValues.dateValue,
        time: initialValues.timeValue
    }), 2), correctDates = _useState1[0], setCorrectDates = _useState1[1];
    var calendarGridValue = initialValues.dateValue;
    var timeGridValue = initialValues.timeValue;
    _datejs.customDayjs.locale(lang);
    var timeVisibleValue = timeGridValue ? (0, _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 = (0, _datejs.customDayjs)(originalDate).quarter() - 1;
        return {
            name: _utils.QUARTER_NAMES[quarterIndex],
            fullValue: [
                originalDate,
                endQuarter
            ]
        };
    };
    var isDateEqualEdge = function isDateEqualEdge(dateEdge) {
        if (!dateEdge) {
            return false;
        }
        var normalizedEdgeDate = (0, _datejs.customDayjs)(dateEdge);
        normalizedEdgeDate.set('hours', 0);
        normalizedEdgeDate.set('minutes', 0);
        normalizedEdgeDate.set('seconds', 0);
        var normalizedCurrentDate = (0, _datejs.customDayjs)(correctDates.calendar);
        normalizedCurrentDate.set('hours', 0);
        normalizedCurrentDate.set('minutes', 0);
        normalizedCurrentDate.set('seconds', 0);
        if (normalizedCurrentDate.isSame(normalizedEdgeDate)) {
            return true;
        }
        return false;
    };
    var getFormattedCorrectInput = function getFormattedCorrectInput(param) {
        var originalDate = param.originalDate, formattedDate = param.formattedDate, dateValue = param.dateValue, timeValue = param.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 _ref = maskWithFormat ? (0, _getMaskedValue.getMaskedValue)({
            value: value,
            format: format,
            delimiters: delimiters,
            prevValue: inputValue,
            selectionStart: selectionStart
        }) : {
            formattedValue: value,
            selectionStart: selectionStart
        }, formattedValue = _ref.formattedValue, newSelectionStart = _ref.selectionStart;
        var _getFormattedDateTime = (0, _utils1.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 _getFormattedCorrectInput = getFormattedCorrectInput({
            originalDate: originalDate,
            formattedDate: formattedDate,
            dateValue: dateValue,
            timeValue: timeValue
        }), inputCorrectValue = _getFormattedCorrectInput.input;
        setCorrectDates(function(prevCorrectDates) {
            return _object_spread_props(_object_spread({}, 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 _getFormattedDateTime = (0, _utils1.getFormattedDateTime)({
            value: date,
            lang: lang,
            format: format,
            dateFormat: dateFormat,
            timeFormat: timeFormat,
            includeEdgeDates: includeEdgeDates,
            min: min,
            max: max
        }), formattedDate = _getFormattedDateTime.formattedDate, isoDate = _getFormattedDateTime.isoDate, originalDate = _getFormattedDateTime.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 = (0, _datejs.customDayjs)(date);
        if (correctDates.time) {
            var correctTimeDate = (0, _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 = (0, _utils1.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 _object_spread_props(_object_spread({}, 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 ? void 0 : time.value)) {
            return;
        }
        _datejs.customDayjs.locale(lang);
        var rawDate;
        if (!correctDates.calendar) {
            if (dateOnTimeSelectOnly) {
                rawDate = (0, _datejs.customDayjs)(dateOnTimeSelectOnly);
            } else {
                rawDate = (0, _datejs.customDayjs)();
            }
        } else {
            rawDate = (0, _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 _normalizeDateTime = (0, _utils1.normalizeDateTime)({
            originalDate: rawDate.toDate(),
            lang: lang,
            format: format,
            includeEdgeDates: includeEdgeDates,
            min: min,
            max: max
        }), normalizedDate = _normalizeDateTime.normalizedDate, formattedNormalizedDate = _normalizeDateTime.formattedNormalizedDate;
        var isoDate = normalizedDate.toISOString();
        var quarterInfo = getQuarterInfo(normalizedDate);
        setCorrectDates(function(prevCorrectDates) {
            return _object_spread_props(_object_spread({}, 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 _getFormattedDateTime = (0, _utils1.getFormattedDateTime)({
            value: externalDate,
            lang: lang,
            format: format,
            dateFormat: dateFormat,
            timeFormat: timeFormat,
            includeEdgeDates: includeEdgeDates,
            min: min,
            max: max
        }), formattedDate = _getFormattedDateTime.formattedDate, originalDate = _getFormattedDateTime.originalDate, dateValue = _getFormattedDateTime.dateValue, timeValue = _getFormattedDateTime.timeValue;
        var _getFormattedCorrectInput = getFormattedCorrectInput({
            originalDate: originalDate,
            formattedDate: formattedDate,
            dateValue: dateValue,
            timeValue: timeValue
        }), inputCorrectValue = _getFormattedCorrectInput.input;
        setCorrectDates(function(prevCorrectDates) {
            return _object_spread_props(_object_spread({}, 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);
        }
    };
    return {
        format: format,
        dateVisibleValue: dateVisibleValue,
        calendarGridValue: calendarGridValue,
        inputValue: inputValue,
        timeVisibleValue: timeVisibleValue,
        timeColumnsCount: timeColumnsCount,
        errorClass: errorClass,
        successClass: successClass,
        handleChangeValue: handleChangeValue,
        handleSearch: handleSearch,
        handleCalendarPick: handleCalendarPick,
        handleTimePick: handleTimePick,
        handleBlur: handleBlur,
        updateExternalDate: updateExternalDate,
        getQuarterInfo: getQuarterInfo,
        isDateEqualEdge: isDateEqualEdge
    };
};
