'use strict';

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

var _rollupPluginBabelHelpers = require('../../../../_virtual/_rollupPluginBabelHelpers.js');
var React = require('react');
var Calendar_tokens = require('../../Calendar.tokens.js');
var DateStructureItem = require('../DateStructureItem/DateStructureItem.js');
var CalendarMonths_styles = require('./CalendarMonths.styles.js');
var useMonths = require('../../hooks/useMonths.js');
var constants = require('../../utils/constants.js');
var calendarGridHelper = require('../../utils/calendarGridHelper.js');
var calendarRangeHelper = require('../../utils/calendarRangeHelper.js');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var React__default = /*#__PURE__*/_interopDefault(React);

/**
 * Компонент месяцев в календаре.
 */
var CalendarMonths = function CalendarMonths(_ref) {
  var currentDate = _ref.date,
    value = _ref.value,
    selectIndexes = _ref.selectIndexes,
    eventList = _ref.eventList,
    disabledList = _ref.disabledList,
    min = _ref.min,
    max = _ref.max,
    outerRefs = _ref.outerRefs,
    isDouble = _ref.isDouble,
    isSecond = _ref.isSecond,
    hoveredMonth = _ref.hoveredMonth,
    onChangeMonth = _ref.onChangeMonth,
    onHoverMonth = _ref.onHoverMonth,
    onSetSelected = _ref.onSetSelected,
    onTriggerEventTooltip = _ref.onTriggerEventTooltip,
    onKeyDown = _ref.onKeyDown,
    locale = _ref.locale;
  var minDate = min ? new Date(min.getFullYear(), min.getMonth(), 1) : undefined;
  var maxDate = max ? new Date(max.getFullYear(), max.getMonth() + 1, 0) : undefined;
  var _useMonths = useMonths.useMonths({
      date: currentDate,
      value: value,
      eventList: eventList,
      disabledList: disabledList,
      min: minDate,
      max: maxDate,
      locale: locale
    }),
    _useMonths2 = _rollupPluginBabelHelpers.slicedToArray(_useMonths, 2),
    months = _useMonths2[0],
    selected = _useMonths2[1];
  var selectedRef = React.useRef(selected);
  var onSetSelectedRef = React.useRef(onSetSelected);
  var noopRef = React.useRef(null);
  var offset = isSecond ? constants.ROW_MONTH_STEP : 0;
  var monthItemTokens = _rollupPluginBabelHelpers.defineProperty(_rollupPluginBabelHelpers.defineProperty(_rollupPluginBabelHelpers.defineProperty(_rollupPluginBabelHelpers.defineProperty(_rollupPluginBabelHelpers.defineProperty(_rollupPluginBabelHelpers.defineProperty(_rollupPluginBabelHelpers.defineProperty(_rollupPluginBabelHelpers.defineProperty({}, "".concat(Calendar_tokens.innerTokens.dateStructureFontFamily), "var(".concat(Calendar_tokens.tokens.calendarMonthFontFamily, ")")), "".concat(Calendar_tokens.innerTokens.dateStructureFontSize), "var(".concat(Calendar_tokens.tokens.calendarMonthFontSize, ")")), "".concat(Calendar_tokens.innerTokens.dateStructureFontWeight), "var(".concat(Calendar_tokens.tokens.calendarMonthFontWeight, ")")), "".concat(Calendar_tokens.innerTokens.dateStructureFontLineHeight), "var(".concat(Calendar_tokens.tokens.calendarMonthFontLineHeight, ")")), "".concat(Calendar_tokens.innerTokens.dateStructureFontLetterSpacing), "var(".concat(Calendar_tokens.tokens.calendarMonthFontLetterSpacing, ")")), "".concat(Calendar_tokens.innerTokens.dateStructureFontStyle), "var(".concat(Calendar_tokens.tokens.calendarMonthFontStyle, ")")), "".concat(Calendar_tokens.innerTokens.dateStructureSelectedFontWeight), "var(".concat(Calendar_tokens.tokens.calendarMonthSelectedFontWeight, ")")), "".concat(Calendar_tokens.innerTokens.dateStructureBorderRadius), "var(".concat(Calendar_tokens.tokens.calendarMonthItemBorderRadius, ")"));
  var getSelectedDate = React.useCallback(function (event) {
    var _event$currentTarget$ = event.currentTarget.dataset,
      day = _event$currentTarget$.day,
      monthIndex = _event$currentTarget$.monthIndex,
      year = _event$currentTarget$.year;
    var selectedDate = {
      day: Number(day),
      monthIndex: Number(monthIndex),
      year: Number(year)
    };
    if (!calendarGridHelper.canSelectDate(selectedDate, value, disabledList)) {
      return;
    }
    return selectedDate;
  }, [disabledList, value]);
  var handleOnChangeMonth = React.useCallback(function (i, j) {
    return function (event) {
      /**
       * нужно вызвать stopImmediatePropagation для случаев, когда
       * обработчик события onClick навешивается снаружи.
       * Как, например, в компоненте Popup
       */
      event.nativeEvent.stopImmediatePropagation();
      var selectedDate = getSelectedDate(event);
      if (!selectedDate) {
        return;
      }
      onChangeMonth(selectedDate, [i + offset, j]);
      if (calendarRangeHelper.isSelectProcess(value)) {
        onHoverMonth === null || onHoverMonth === void 0 || onHoverMonth(undefined);
      }
    };
  }, [getSelectedDate, onChangeMonth, offset, value, onHoverMonth]);
  var handleOnHoverMonth = React.useCallback(function (event) {
    var selectedDate = getSelectedDate(event);
    var isSelectedDone = Array.isArray(value) && value[0] && value[1];
    if (!selectedDate || !Array.isArray(value) || isSelectedDone) {
      return;
    }
    onHoverMonth === null || onHoverMonth === void 0 || onHoverMonth(selectedDate);
  }, [getSelectedDate, onHoverMonth, value]);
  var handleMouseOutGrid = function handleMouseOutGrid() {
    onHoverMonth === null || onHoverMonth === void 0 || onHoverMonth(undefined);
    onTriggerEventTooltip === null || onTriggerEventTooltip === void 0 || onTriggerEventTooltip(noopRef, []);
  };
  var getRefs = React.useCallback(function (element, i, j) {
    if (!outerRefs.current[i + offset]) {
      outerRefs.current[i + offset] = [];
    }
    outerRefs.current[i + offset][j] = element;
  }, [offset, outerRefs]);
  React.useEffect(function () {
    if (selectedRef.current) {
      var _onSetSelectedRef$cur;
      (_onSetSelectedRef$cur = onSetSelectedRef.current) === null || _onSetSelectedRef$cur === void 0 || _onSetSelectedRef$cur.call(onSetSelectedRef, selectedRef.current);
    }
  }, []);
  return /*#__PURE__*/React__default.default.createElement(CalendarMonths_styles.StyledCalendarMonths, {
    role: "grid",
    "aria-labelledby": "id-grid-label",
    onKeyDown: onKeyDown,
    onMouseLeave: handleMouseOutGrid
  }, months.map(function (month, i) {
    return /*#__PURE__*/React__default.default.createElement(React.Fragment, {
      key: i
    }, month.map(function (_ref2, j) {
      var monthName = _ref2.monthName,
        monthIndex = _ref2.monthIndex,
        isSelected = _ref2.isSelected,
        isCurrent = _ref2.isCurrent,
        monthFullName = _ref2.monthFullName,
        date = _ref2.date,
        events = _ref2.events,
        isOutOfMinMaxRange = _ref2.isOutOfMinMaxRange,
        inRange = _ref2.inRange,
        disabled = _ref2.disabled,
        disabledArrowKey = _ref2.disabledArrowKey,
        disabledDates = _ref2.disabledDates;
      return /*#__PURE__*/React__default.default.createElement(DateStructureItem.DateStructureItem, {
        ref: function ref(element) {
          return getRefs(element, i, j);
        },
        style: monthItemTokens,
        eventList: events,
        disabled: disabled,
        day: date.day,
        year: date.year,
        monthIndex: 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: calendarRangeHelper.isSameDay(date, hoveredMonth),
        inRange: calendarRangeHelper.getInRange(value, date, hoveredMonth, inRange),
        sideInRange: calendarRangeHelper.getSideInRange(value, date, hoveredMonth, isSelected),
        onClick: disabled ? undefined : handleOnChangeMonth(i, j),
        onMouseOver: disabled ? undefined : handleOnHoverMonth,
        onTriggerEventTooltip: onTriggerEventTooltip,
        key: "StyledMonth-".concat(i, "-").concat(j),
        role: "gridcell",
        "aria-label": monthFullName,
        disabledArrowKey: disabledArrowKey,
        disabledMonths: disabledDates,
        isDayInCurrentMonth: true
      }, monthName);
    }));
  }));
};

exports.CalendarMonths = CalendarMonths;
