"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "CalendarYears", {
    enumerable: true,
    get: function() {
        return CalendarYears;
    }
});
var _react = /*#__PURE__*/ _interop_require_wildcard(require("react"));
var _hooks = require("../../hooks");
var _Calendartokens = require("../../Calendar.tokens");
var _utils = require("../../utils");
var _DateStructureItem = require("../DateStructureItem/DateStructureItem");
var _CalendarYearsstyles = require("./CalendarYears.styles");
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 _getRequireWildcardCache(nodeInterop) {
    if (typeof WeakMap !== "function") return null;
    var cacheBabelInterop = new WeakMap();
    var cacheNodeInterop = new WeakMap();
    return (_getRequireWildcardCache = function(nodeInterop) {
        return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
    })(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
    if (!nodeInterop && obj && obj.__esModule) {
        return obj;
    }
    if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
        return {
            default: obj
        };
    }
    var cache = _getRequireWildcardCache(nodeInterop);
    if (cache && cache.has(obj)) {
        return cache.get(obj);
    }
    var newObj = {
        __proto__: null
    };
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for(var key in obj){
        if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
            var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
            if (desc && (desc.get || desc.set)) {
                Object.defineProperty(newObj, key, desc);
            } else {
                newObj[key] = obj[key];
            }
        }
    }
    newObj.default = obj;
    if (cache) {
        cache.set(obj, newObj);
    }
    return newObj;
}
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 _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 CalendarYears = function CalendarYears(param) {
    var currentDate = param.date, value = param.value, startYear = param.startYear, selectIndexes = param.selectIndexes, eventList = param.eventList, disabledList = param.disabledList, min = param.min, max = param.max, outerRefs = param.outerRefs, isDouble = param.isDouble, isSecond = param.isSecond, hoveredYear = param.hoveredYear, onChangeYear = param.onChangeYear, onHoverYear = param.onHoverYear, onSetSelected = param.onSetSelected, onTriggerEventTooltip = param.onTriggerEventTooltip, onKeyDown = param.onKeyDown;
    var minDate = min ? new Date(min.getFullYear(), 0, 1) : undefined;
    var maxDate = max ? new Date(max.getFullYear(), 11, 31) : undefined;
    var _useYears = _sliced_to_array((0, _hooks.useYears)({
        date: currentDate,
        value: value,
        startYear: startYear,
        eventList: eventList,
        disabledList: disabledList,
        min: minDate,
        max: maxDate
    }), 2), years = _useYears[0], selected = _useYears[1];
    var selectedRef = (0, _react.useRef)(selected);
    var onSetSelectedRef = (0, _react.useRef)(onSetSelected);
    var noopRef = (0, _react.useRef)(null);
    var offset = isSecond ? _utils.ROW_YEAR_STEP : 0;
    var _obj;
    var yearItemTokens = (_obj = {}, _define_property(_obj, "".concat(_Calendartokens.innerTokens.dateStructureFontFamily), "var(".concat(_Calendartokens.tokens.calendarYearFontFamily, ")")), _define_property(_obj, "".concat(_Calendartokens.innerTokens.dateStructureFontSize), "var(".concat(_Calendartokens.tokens.calendarYearFontSize, ")")), _define_property(_obj, "".concat(_Calendartokens.innerTokens.dateStructureFontWeight), "var(".concat(_Calendartokens.tokens.calendarYearFontWeight, ")")), _define_property(_obj, "".concat(_Calendartokens.innerTokens.dateStructureFontLineHeight), "var(".concat(_Calendartokens.tokens.calendarYearFontLineHeight, ")")), _define_property(_obj, "".concat(_Calendartokens.innerTokens.dateStructureFontLetterSpacing), "var(".concat(_Calendartokens.tokens.calendarYearFontLetterSpacing, ")")), _define_property(_obj, "".concat(_Calendartokens.innerTokens.dateStructureFontStyle), "var(".concat(_Calendartokens.tokens.calendarYearFontStyle, ")")), _define_property(_obj, "".concat(_Calendartokens.innerTokens.dateStructureSelectedFontWeight), "var(".concat(_Calendartokens.tokens.calendarYearSelectedFontWeight, ")")), _define_property(_obj, "".concat(_Calendartokens.innerTokens.dateStructureBorderRadius), "var(".concat(_Calendartokens.tokens.calendarYearItemBorderRadius, ")")), _obj);
    var getSelectedDate = (0, _react.useCallback)(function(event) {
        var _event_currentTarget_dataset = event.currentTarget.dataset, day = _event_currentTarget_dataset.day, monthIndex = _event_currentTarget_dataset.monthIndex, year = _event_currentTarget_dataset.year;
        var selectedDate = {
            day: Number(day),
            monthIndex: Number(monthIndex),
            year: Number(year)
        };
        if (!(0, _utils.canSelectDate)(selectedDate, value, disabledList)) {
            return;
        }
        return selectedDate;
    }, [
        disabledList,
        value
    ]);
    var handleOnChangeYear = (0, _react.useCallback)(function(i, j) {
        return function(event) {
            /**
             * нужно вызвать stopImmediatePropagation для случаев, когда
             * обработчик события onClick навешивается снаружи.
             * Как, например, в компоненте Popup
             */ event.nativeEvent.stopImmediatePropagation();
            var selectedDate = getSelectedDate(event);
            if (!selectedDate) {
                return;
            }
            onChangeYear(selectedDate, [
                i + offset,
                j
            ]);
            if ((0, _utils.isSelectProcess)(value)) {
                onHoverYear === null || onHoverYear === void 0 ? void 0 : onHoverYear(undefined);
            }
        };
    }, [
        getSelectedDate,
        onChangeYear,
        offset,
        value,
        onHoverYear
    ]);
    var handleOnHoverYear = (0, _react.useCallback)(function(event) {
        var selectedDate = getSelectedDate(event);
        var isSelectedDone = Array.isArray(value) && value[0] && value[1];
        if (!selectedDate || !Array.isArray(value) || isSelectedDone) {
            return;
        }
        onHoverYear === null || onHoverYear === void 0 ? void 0 : onHoverYear(selectedDate);
    }, [
        getSelectedDate,
        onHoverYear,
        value
    ]);
    var handleMouseOutGrid = function handleMouseOutGrid() {
        onHoverYear === null || onHoverYear === void 0 ? void 0 : onHoverYear(undefined);
        onTriggerEventTooltip === null || onTriggerEventTooltip === void 0 ? void 0 : onTriggerEventTooltip(noopRef, []);
    };
    var getRefs = (0, _react.useCallback)(function(element, i, j) {
        if (!outerRefs.current[i + offset]) {
            outerRefs.current[i + offset] = [];
        }
        outerRefs.current[i + offset][j] = element;
    }, [
        outerRefs
    ]);
    (0, _react.useEffect)(function() {
        if (selectedRef.current) {
            var _onSetSelectedRef_current;
            (_onSetSelectedRef_current = onSetSelectedRef.current) === null || _onSetSelectedRef_current === void 0 ? void 0 : _onSetSelectedRef_current.call(onSetSelectedRef, selectedRef.current);
        }
    }, []);
    return /*#__PURE__*/ _react.default.createElement(_CalendarYearsstyles.StyledCalendarYears, {
        role: "grid",
        "aria-labelledby": "id-grid-label",
        onKeyDown: onKeyDown,
        onMouseLeave: handleMouseOutGrid
    }, years.map(function(year, i) {
        return /*#__PURE__*/ _react.default.createElement(_react.Fragment, {
            key: i
        }, year.map(function(param, j) {
            var yearValue = param.yearValue, isSelected = param.isSelected, isCurrent = param.isCurrent, date = param.date, events = param.events, isOutOfMinMaxRange = param.isOutOfMinMaxRange, inRange = param.inRange, disabled = param.disabled, disabledArrowKey = param.disabledArrowKey, disabledDates = param.disabledDates;
            return /*#__PURE__*/ _react.default.createElement(_DateStructureItem.DateStructureItem, {
                ref: function ref(element) {
                    return getRefs(element, i, j);
                },
                style: yearItemTokens,
                eventList: events,
                disabled: disabled,
                day: date.day,
                year: yearValue,
                monthIndex: date.monthIndex,
                isFocused: i + offset === (selectIndexes === null || selectIndexes === void 0 ? void 0 : selectIndexes[0]) && j === (selectIndexes === null || selectIndexes === void 0 ? void 0 : selectIndexes[1]) && !isOutOfMinMaxRange,
                isSelected: isSelected,
                isCurrent: isCurrent,
                isDouble: isDouble,
                isHovered: (0, _utils.isSameDay)(date, hoveredYear),
                inRange: (0, _utils.getInRange)(value, date, hoveredYear, inRange),
                sideInRange: (0, _utils.getSideInRange)(value, date, hoveredYear, isSelected),
                onClick: disabled ? undefined : handleOnChangeYear(i, j),
                onMouseOver: disabled ? undefined : handleOnHoverYear,
                onTriggerEventTooltip: onTriggerEventTooltip,
                key: "StyledYear-".concat(i, "-").concat(j),
                role: "gridcell",
                "data-year": yearValue,
                "data-month-index": date.monthIndex,
                "data-day": date.day,
                "aria-label": String(yearValue),
                disabledArrowKey: disabledArrowKey,
                disabledMonths: disabledDates,
                isDayInCurrentMonth: true
            }, yearValue);
        }));
    }));
};
