var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
import React from 'react';
import normalizeWheel from 'normalize-wheel';
import throttle from 'lodash.throttle';
import shallowEqual from 'shallowequal';
import { isInstanceOf } from '../../lib/isInstanceOf.js';
import { InternalDate } from '../../lib/date/InternalDate.js';
import { rootNode } from '../../lib/rootNode/index.js';
import { CommonWrapper } from '../../internal/CommonWrapper/index.js';
import { MAX_DATE, MAX_MONTH, MAX_YEAR, MIN_DATE, MIN_MONTH, MIN_YEAR } from '../../lib/date/constants.js';
import { ThemeContext } from '../../lib/theming/ThemeContext.js';
import { animation } from '../../lib/animation/index.js';
import { isMobile } from '../../lib/client.js';
import { createPropsGetter } from '../../lib/createPropsGetter.js';
import { InternalDateTransformer } from '../../lib/date/InternalDateTransformer.js';
import { withRenderEnvironment } from '../../lib/renderEnvironment/index.js';
import { themeConfig } from './config.js';
import { MonthViewModel } from './MonthViewModel.js';
import * as CalendarScrollEvents from './CalendarScrollEvents.js';
import { Month } from './Month.js';
import { getStyles } from './Calendar.styles.js';
import { create, isGreater, isLess } from './CalendarDateShape.js';
import * as CalendarUtils from './CalendarUtils.js';
import { CalendarContext } from './CalendarContext.js';
import { CalendarDay } from './CalendarDay.js';
export var CalendarDataTids = {
    root: 'Calendar__root',
    month: 'MonthView__month',
    dayCell: 'DayCellView__root',
    headerMonth: 'MonthView__headerMonth',
    headerYear: 'MonthView__headerYear',
};
/**
 * Компонент календаря `Calendar` из DatePicker'а помогает выбирать дату с помощью мыши.
 */
var Calendar = /** @class */ (function (_super) {
    __extends(Calendar, _super);
    function Calendar(props) {
        var _a;
        var _this = _super.call(this, props) || this;
        _this.getProps = createPropsGetter(Calendar_1.defaultProps);
        _this.touchStartY = null;
        /**
         * Прокручивает календарь до переданной даты
         * @public
         */
        _this.scrollToMonth = function (month, year) { return __awaiter(_this, void 0, void 0, function () {
            var monthNative, minDate, maxDate, minMonth, maxMonth, currentMonth, diffInMonths, maxMonthsToAdd, onEnd, monthsToPrependCount, monthsToPrepend_1, monthsToAppendCount_1, monthsToAppend_1;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        monthNative = CalendarUtils.getMonthInNativeFormat(month);
                        if (!this.animation.inProgress()) return [3 /*break*/, 2];
                        this.animation.finish();
                        // FIXME: Dirty hack to await batched updates
                        return [4 /*yield*/, new Promise(function (r) { return setTimeout(r, 0); })];
                    case 1:
                        // FIXME: Dirty hack to await batched updates
                        _a.sent();
                        _a.label = 2;
                    case 2:
                        minDate = this.getDateInNativeFormat(this.getProps().minDate);
                        maxDate = this.getDateInNativeFormat(this.getProps().maxDate);
                        if (minDate && isGreater(minDate, create(32, monthNative, year))) {
                            minMonth = CalendarUtils.getMonthInHumanFormat(minDate.month);
                            this.scrollToMonth(minMonth, minDate.year);
                            return [2 /*return*/];
                        }
                        if (maxDate && isLess(maxDate, create(0, monthNative, year))) {
                            maxMonth = CalendarUtils.getMonthInHumanFormat(maxDate.month);
                            this.scrollToMonth(maxMonth, maxDate.year);
                            return [2 /*return*/];
                        }
                        currentMonth = this.state.months[1];
                        diffInMonths = currentMonth.month + currentMonth.year * 12 - monthNative - year * 12;
                        if (diffInMonths === 0) {
                            this.scrollTo(0);
                            return [2 /*return*/];
                        }
                        maxMonthsToAdd = themeConfig(this.theme).MAX_MONTHS_TO_APPEND_ON_SCROLL;
                        onEnd = function () {
                            _this.setState({
                                months: CalendarUtils.getMonths(monthNative, year),
                                scrollPosition: 0,
                            });
                        };
                        // If scrolling upwards, prepend maximum maxMonthsToAdd months
                        // and scroll to the first month
                        if (diffInMonths > 0) {
                            monthsToPrependCount = Math.min(Math.abs(diffInMonths) - 1, maxMonthsToAdd);
                            monthsToPrepend_1 = Array.from({ length: monthsToPrependCount }, function (_, index) {
                                return MonthViewModel.create(monthNative + index, year);
                            });
                            this.setState(function (state) {
                                return {
                                    months: monthsToPrepend_1.concat(state.months),
                                    scrollPosition: -CalendarUtils.getMonthsHeight(monthsToPrepend_1, _this.theme),
                                };
                            }, function () {
                                var targetPosition = _this.state.months[0].getHeight(_this.theme);
                                _this.scrollTo(targetPosition, onEnd);
                            });
                        }
                        // If scrolling downwards, append maximum maxMonthsToAdd months
                        // and scroll to the last but one month
                        if (diffInMonths < 0) {
                            monthsToAppendCount_1 = Math.min(Math.abs(diffInMonths), maxMonthsToAdd);
                            monthsToAppend_1 = Array.from({ length: monthsToAppendCount_1 }, function (_, index) {
                                return MonthViewModel.create(monthNative + index - monthsToAppendCount_1 + 2, year);
                            });
                            this.setState(function (state) {
                                return { months: state.months.concat(monthsToAppend_1) };
                            }, function () {
                                var targetPosition = -1 * CalendarUtils.getMonthsHeight(_this.state.months.slice(1, -2), _this.theme);
                                _this.scrollTo(targetPosition, onEnd);
                            });
                        }
                        return [2 /*return*/];
                }
            });
        }); };
        _this.handleMonthChange = function (visibleMonths) {
            var _a, _b;
            var currentMonth = visibleMonths[0];
            var changeInfo = {
                month: CalendarUtils.getMonthInHumanFormat(currentMonth.month),
                year: currentMonth.year,
            };
            (_b = (_a = _this.props).onMonthChange) === null || _b === void 0 ? void 0 : _b.call(_a, changeInfo);
        };
        _this.getViewModel = function (item) { return item[1]; };
        _this.renderMain = function () {
            var monthsForRender = _this.getVisibleMonths(_this.state);
            var wrapperStyle = { height: themeConfig(_this.theme).WRAPPER_HEIGHT };
            var props = _this.getProps();
            var context = {
                value: _this.getDateInNativeFormat(props.value),
                minDate: _this.getDateInNativeFormat(props.minDate),
                maxDate: _this.getDateInNativeFormat(props.maxDate),
                isHoliday: props.isHoliday,
                renderDay: props.renderDay,
                today: CalendarUtils.getTodayDate(),
                onDateClick: _this.handleDateClick,
            };
            return (React.createElement(CommonWrapper, __assign({ rootNodeRef: _this.setRootNode }, props),
                React.createElement("div", { ref: _this.refRoot, "data-tid": CalendarDataTids.root, className: _this.cx(_this.styles.root(_this.theme)) },
                    React.createElement("div", { style: wrapperStyle, className: _this.styles.wrapper() },
                        React.createElement(CalendarContext.Provider, { value: context }, monthsForRender.map(_this.renderMonth, _this))),
                    React.createElement("div", { className: _this.styles.separator(_this.theme) }))));
        };
        _this.refRoot = function (element) {
            if (!_this.root && element) {
                if (isMobile) {
                    element.addEventListener('touchstart', _this.handleTouchStart);
                    element.addEventListener('touchmove', _this.throttledHandleTouchMove);
                }
                else {
                    element.addEventListener('wheel', _this.handleWheel, { passive: false });
                }
            }
            if (_this.root && !element) {
                if (isMobile) {
                    _this.root.removeEventListener('touchstart', _this.handleTouchStart);
                    _this.root.removeEventListener('touchmove', _this.throttledHandleTouchMove);
                }
                else {
                    _this.root.removeEventListener('wheel', _this.handleWheel);
                }
            }
            _this.root = element;
        };
        _this.handleDateClick = function (dateShape) {
            var _a, _b;
            var value = InternalDateTransformer.dateToHumanString(dateShape);
            (_b = (_a = _this.props).onValueChange) === null || _b === void 0 ? void 0 : _b.call(_a, value);
        };
        _this.handleMonthYearChange = function (monthNative, year) {
            var month = CalendarUtils.getMonthInHumanFormat(monthNative);
            _this.scrollToMonth(month, year);
        };
        _this.executeAnimations = function (pixelY) {
            _this.setState(function (_a) {
                var months = _a.months, scrollPosition = _a.scrollPosition;
                var targetPosition = CalendarUtils.calculateScrollPosition(months, scrollPosition, pixelY, _this.theme).scrollPosition;
                return { scrollTarget: targetPosition };
            }, _this.handleWheelEnd);
            _this.animation.animate(pixelY, function (deltaY) {
                // FIXME: Typescript not resolving setState cb type
                _this.setState(CalendarUtils.applyDelta(deltaY, _this.theme));
            });
            CalendarScrollEvents.emit();
        };
        _this.handleTouchStart = function (event) {
            if (!isInstanceOf(event, _this.globalObject.TouchEvent)) {
                return;
            }
            var clientY = event.targetTouches[0].clientY;
            _this.touchStartY = clientY;
        };
        _this.handleTouchMove = function (event) {
            if (!isInstanceOf(event, _this.globalObject.TouchEvent)) {
                return;
            }
            var clientY = event.changedTouches[0].clientY;
            var deltaY = (_this.touchStartY || 0) - clientY;
            _this.touchStartY = clientY;
            _this.executeAnimations(deltaY);
        };
        _this.throttledHandleTouchMove = throttle(_this.handleTouchMove, 10);
        _this.handleWheel = function (event) {
            if (!isInstanceOf(event, _this.globalObject.WheelEvent)) {
                return;
            }
            event.preventDefault();
            var pixelY = normalizeWheel(event).pixelY;
            _this.executeAnimations(pixelY);
        };
        _this.handleWheelEnd = function () {
            if (_this.wheelEndTimeout) {
                clearTimeout(_this.wheelEndTimeout);
            }
            _this.wheelEndTimeout = setTimeout(_this.scrollToNearestWeek, 300);
        };
        _this.scrollToNearestWeek = function () {
            var _a = _this.state, scrollTarget = _a.scrollTarget, scrollDirection = _a.scrollDirection;
            var thresholdHeight = themeConfig(_this.theme).MONTH_TITLE_OFFSET_HEIGHT + themeConfig(_this.theme).DAY_HEIGHT;
            if (scrollTarget < thresholdHeight) {
                var targetPosition_1 = 0;
                if (scrollDirection < 0) {
                    targetPosition_1 = thresholdHeight;
                }
                _this.setState({ scrollTarget: targetPosition_1 }, function () {
                    var amount = scrollTarget - targetPosition_1;
                    _this.animation.animate(amount, function (deltaY) {
                        // FIXME: Typescript not resolving setState cb type
                        _this.setState(CalendarUtils.applyDelta(deltaY, _this.theme));
                    });
                });
            }
        };
        _this.scrollTo = function (pos, onEnd) {
            var scrollAmmount = pos - _this.state.scrollPosition;
            return _this.scrollAmount(scrollAmmount, onEnd);
        };
        _this.scrollAmount = function (scrollAmmount, onEnd) {
            return _this.animation.animate(scrollAmmount, function (deltaY) {
                _this.setState(function (_a) {
                    var scrollPosition = _a.scrollPosition;
                    return ({
                        scrollPosition: scrollPosition + deltaY,
                    });
                });
            }, onEnd);
        };
        var _b = _this.getProps(), minDate = _b.minDate, maxDate = _b.maxDate, value = _b.value;
        var minDateShape = _this.getDateInNativeFormat(minDate);
        var maxDateShape = _this.getDateInNativeFormat(maxDate);
        var dateShape = _this.getDateInNativeFormat(value);
        var today = CalendarUtils.getTodayDate();
        var initialDate = CalendarUtils.getInitialDate({
            today: today,
            date: dateShape,
            minDate: minDateShape,
            maxDate: maxDateShape,
        });
        var initialMonth = _this.props.initialMonth
            ? CalendarUtils.getMonthInNativeFormat(_this.props.initialMonth)
            : initialDate.month;
        var initialYear = (_a = _this.props.initialYear) !== null && _a !== void 0 ? _a : initialDate.year;
        _this.state = {
            scrollPosition: 0,
            months: CalendarUtils.getMonths(initialMonth, initialYear),
            scrollDirection: 1,
            scrollTarget: 0,
        };
        return _this;
    }
    Calendar_1 = Calendar;
    Calendar.formatDate = function (date, month, year) {
        return new InternalDate().setComponents({ date: date, month: month, year: year }).toString({ withPad: true });
    };
    Calendar.prototype.componentDidUpdate = function (prevProps, prevState) {
        var _a = this.props, value = _a.value, onMonthChange = _a.onMonthChange;
        if (value && !shallowEqual(value, prevProps.value)) {
            var date = new InternalDate().parseValue(value).getComponentsLikeNumber();
            this.scrollToMonth(date.month, date.year);
        }
        if (onMonthChange) {
            var visibleMonthsModels = this.getVisibleMonths(this.state).map(this.getViewModel);
            var prevFirstVisibleMonthModels = this.getVisibleMonths(prevState).map(this.getViewModel);
            if (visibleMonthsModels.length > 0 && prevFirstVisibleMonthModels.length > 0) {
                var currentMonth = visibleMonthsModels[0].month;
                var prevCurrentMonth = prevFirstVisibleMonthModels[0].month;
                if (currentMonth !== prevCurrentMonth) {
                    this.handleMonthChange(visibleMonthsModels);
                }
            }
        }
    };
    Calendar.prototype.componentWillUnmount = function () {
        if (this.animation.inProgress()) {
            this.animation.cancel();
        }
    };
    Calendar.prototype.render = function () {
        var _this = this;
        this.styles = getStyles(this.emotion);
        this.animation = animation(this.globalObject);
        return (React.createElement(ThemeContext.Consumer, null, function (theme) {
            _this.theme = theme;
            return _this.renderMain();
        }));
    };
    Calendar.prototype.renderMonth = function (_a) {
        var top = _a[0], month = _a[1];
        return (React.createElement(Month, { key: month.month + '-' + month.year, top: top, month: month, onMonthYearChange: this.handleMonthYearChange }));
    };
    Calendar.prototype.getDateInNativeFormat = function (date) {
        return new InternalDate().parseValue(date).toNativeFormat();
    };
    Calendar.prototype.getMonthPositions = function (months, scrollPosition) {
        var positions = [scrollPosition - months[0].getHeight(this.theme)];
        for (var i = 1; i < months.length; i++) {
            var position = positions[i - 1] + months[i - 1].getHeight(this.theme);
            positions.push(position);
        }
        return positions;
    };
    Calendar.prototype.getVisibleMonths = function (state) {
        var _this = this;
        var months = state.months, scrollPosition = state.scrollPosition;
        var positions = this.getMonthPositions(months, scrollPosition);
        return months
            .map(function (x, i) { return [positions[i], x]; })
            .filter(function (_a) {
            var top = _a[0], month = _a[1];
            return CalendarUtils.isMonthVisible(top, month, _this.theme);
        });
    };
    var Calendar_1;
    Calendar.__KONTUR_REACT_UI__ = 'Calendar';
    Calendar.displayName = 'Calendar';
    Calendar.Day = CalendarDay;
    Calendar.defaultProps = {
        minDate: Calendar_1.formatDate(MIN_DATE, MIN_MONTH, MIN_YEAR),
        maxDate: Calendar_1.formatDate(MAX_DATE, MAX_MONTH, MAX_YEAR),
        isHoliday: function (_day, isWeekend) { return isWeekend; },
    };
    Calendar = Calendar_1 = __decorate([
        withRenderEnvironment,
        rootNode
    ], Calendar);
    return Calendar;
}(React.Component));
export { Calendar };
//# sourceMappingURL=Calendar.js.map