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;
};
import React from 'react';
import { Popup } from '../../internal/Popup/index.js';
import { LocaleContext } from '../../lib/locale/index.js';
import { locale } from '../../lib/locale/decorators.js';
import { InternalDateGetter } from '../../lib/date/InternalDateGetter.js';
import { ArrowAUpIcon16Light } from '../../internal/icons2022/ArrowAUpIcon/ArrowAUp16Light.js';
import { ThemeFactory } from '../../lib/theming/ThemeFactory.js';
import { InternalDate } from '../../lib/date/InternalDate.js';
import { MAX_FULLDATE, MIN_FULLDATE } from '../../lib/date/constants.js';
import { InternalDateOrder, InternalDateSeparator, InternalDateValidateCheck } from '../../lib/date/types.js';
import { DateInput } from '../DateInput/index.js';
import { filterProps } from '../../lib/filterProps.js';
import { CommonWrapper } from '../../internal/CommonWrapper/index.js';
import { isMobile } from '../../lib/client.js';
import { NativeDateInput } from '../../internal/NativeDateInput/index.js';
import { getRootNode, rootNode } from '../../lib/rootNode/index.js';
import { isNonNullable } from '../../lib/utils.js';
import { createPropsGetter } from '../../lib/createPropsGetter.js';
import { Calendar } from '../Calendar/index.js';
import { ThemeContext } from '../../lib/theming/ThemeContext.js';
import { Button } from '../Button/index.js';
import { getTodayDate } from '../Calendar/CalendarUtils.js';
import { responsiveLayout } from '../ResponsiveLayout/decorator.js';
import { getMenuPositions } from '../../lib/getMenuPositions.js';
import { ZIndex } from '../../internal/ZIndex/index.js';
import { withRenderEnvironment } from '../../lib/renderEnvironment/index.js';
import { getStyles } from './DatePicker.styles.js';
import { DatePickerLocaleHelper } from './locale/index.js';
import { MobilePicker } from './MobilePicker.js';
var INPUT_PASS_PROPS = {
    autoFocus: true,
    disabled: true,
    warning: true,
    error: true,
    size: true,
    onKeyDown: true,
};
export var MIN_WIDTH = 120;
export var DatePickerDataTids = {
    root: 'DatePicker__root',
    input: 'DatePicker__input',
    label: 'DatePicker__label',
    pickerRoot: 'Picker__root',
    pickerTodayWrapper: 'Picker__todayWrapper',
};
/**
 * Поле `DatePicker` помогает вводить дату с клавиатуры или выбирать ее с помощью мыши.
 *
 * Используйте поле с датой, когда нужно ввести дату в формате ДД.ММ.ГГГГ.
 *
 * Поле с датой отличается от обычного поля ввода наличием иконки, маски и блока календаря.
 */
var DatePicker = /** @class */ (function (_super) {
    __extends(DatePicker, _super);
    function DatePicker() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.getProps = createPropsGetter(DatePicker_1.defaultProps);
        _this.canOpenPopup = true;
        _this.state = { opened: false, canUseMobileNativeDatePicker: false, today: getTodayDate() };
        _this.input = null;
        _this.focused = false;
        _this.renderMain = function (props) {
            var picker = null;
            var _a = _this.getProps(), minDate = _a.minDate, maxDate = _a.maxDate, menuPos = _a.menuPos, menuAlign = _a.menuAlign;
            var isMobile = _this.isMobileLayout;
            if (_this.state.opened) {
                if (isMobile) {
                    picker = (React.createElement(MobilePicker, { value: _this.props.value, minDate: _this.parseValueToDate(minDate), maxDate: _this.parseValueToDate(maxDate), onValueChange: _this.props.onValueChange, enableTodayLink: _this.props.enableTodayLink, isHoliday: _this.props.isHoliday, onCloseRequest: _this.handleMobileCloseRequest, renderDay: props.renderDay, onMonthChange: props.onMonthChange }));
                }
                else {
                    picker = (React.createElement(LocaleContext.Provider, { value: {
                            locale: {
                                Calendar: {
                                    months: _this.locale.months,
                                    dayCellChooseDateAriaLabel: _this.locale.dayCellChooseDateAriaLabel,
                                    selectMonthAriaLabel: _this.locale.selectMonthAriaLabel,
                                    selectYearAriaLabel: _this.locale.selectYearAriaLabel,
                                    selectChosenAriaLabel: _this.locale.selectChosenAriaLabel,
                                },
                            },
                        } },
                        React.createElement(Popup, { opened: true, hasShadow: true, priority: ZIndex.priorities.PopupMenu, positions: getMenuPositions(menuPos, menuAlign), "data-tid": DatePickerDataTids.root, anchorElement: _this.getParent(), margin: parseInt(_this.theme.datePickerMenuOffsetY) },
                            React.createElement("div", { "data-tid": DatePickerDataTids.pickerRoot, className: _this.styles.calendarWrapper(_this.theme), onMouseDown: function (e) { return e.preventDefault(); } },
                                React.createElement(Calendar, { maxDate: _this.parseValueToDate(maxDate), minDate: _this.parseValueToDate(minDate), onValueChange: _this.handleValueChange, isHoliday: _this.props.isHoliday, value: _this.parseValueToDate(_this.props.value), renderDay: _this.props.renderDay, onMonthChange: _this.props.onMonthChange }),
                                _this.props.enableTodayLink && _this.renderTodayLink(),
                                ' '))));
                }
            }
            return (React.createElement("label", { className: _this.styles.root(), style: _this.getRootStyle(), onMouseEnter: _this.props.onMouseEnter, onMouseLeave: _this.props.onMouseLeave, onMouseOver: _this.props.onMouseOver, "data-tid": DatePickerDataTids.label },
                React.createElement(DateInput, __assign({ id: _this.props.id }, filterProps(props, INPUT_PASS_PROPS), { ref: _this.getInputRef, value: _this.props.value || '', width: "100%", withIcon: true, minDate: minDate, maxDate: maxDate, onBlur: isMobile ? undefined : _this.handleBlur, onFocus: _this.handleFocus, onValueChange: _this.props.onValueChange, onClick: _this.openPickerPopup, onKeyDown: _this.handleKeyDown, "data-tid": DatePickerDataTids.input })),
                _this.state.canUseMobileNativeDatePicker ? (React.createElement(NativeDateInput, { onValueChange: _this.props.onValueChange, value: _this.props.value || '', minDate: minDate, maxDate: maxDate, disabled: _this.props.disabled })) : (picker)));
        };
        _this.getParent = function () {
            return getRootNode(_this);
        };
        _this.getRootStyle = function () {
            var width = _this.props.width;
            return isNonNullable(width) ? { width: width } : { minWidth: MIN_WIDTH };
        };
        _this.getInputRef = function (ref) {
            _this.input = ref;
        };
        _this.openPickerPopup = function () {
            _this.setState({ opened: true });
        };
        _this.handleFocus = function () {
            if (_this.focused) {
                return;
            }
            if (!_this.canOpenPopup) {
                _this.canOpenPopup = true;
            }
            else {
                _this.openPickerPopup();
            }
            _this.focused = true;
            if (_this.props.onFocus) {
                _this.props.onFocus();
            }
        };
        _this.handleKeyDown = function (e) {
            if (!_this.state.opened) {
                _this.openPickerPopup();
            }
            if (_this.props.onKeyDown) {
                _this.props.onKeyDown(e);
            }
        };
        _this.handleBlur = function () {
            if (!_this.focused) {
                return;
            }
            _this.focused = false;
            _this.close();
            if (_this.props.onBlur) {
                _this.props.onBlur();
            }
        };
        _this.handleValueChange = function (value) {
            _this.handleSelect(value);
            _this.blur();
        };
        _this.handleSelect = function (value) {
            if (!value) {
                return null;
            }
            if (_this.props.onValueChange) {
                _this.props.onValueChange(value);
            }
        };
        _this.handleMobileCloseRequest = function () {
            _this.close();
        };
        return _this;
    }
    DatePicker_1 = DatePicker;
    DatePicker.prototype.componentDidMount = function () {
        if (this.props.useMobileNativeDatePicker && isMobile) {
            this.setState({
                canUseMobileNativeDatePicker: true,
            });
        }
        if (this.props.autoFocus) {
            this.focus();
        }
    };
    DatePicker.prototype.componentDidUpdate = function (prevProps, prevState) {
        var disabled = this.props.disabled;
        var opened = this.state.opened;
        if (disabled && opened) {
            this.close();
        }
        if (prevState.opened && !opened && this.isMobileLayout) {
            this.handleBlur();
        }
    };
    /**
     * @public
     */
    DatePicker.prototype.blur = function () {
        if (this.input) {
            this.input.blur();
        }
        this.handleBlur();
    };
    /**
     * @public
     */
    DatePicker.prototype.focus = function (opts) {
        if (this.props.disabled) {
            return;
        }
        if (opts === null || opts === void 0 ? void 0 : opts.withoutOpenDropdown) {
            this.canOpenPopup = false;
        }
        if (this.input) {
            this.input.focus();
        }
    };
    /**
     * Закрывает выпадашку выбора дня
     * @public
     */
    DatePicker.prototype.close = function () {
        this.setState({ opened: false });
    };
    DatePicker.prototype.render = function () {
        var _this = this;
        this.styles = getStyles(this.emotion);
        return (React.createElement(ThemeContext.Consumer, null, function (theme) {
            _this.theme = theme;
            return (React.createElement(ThemeContext.Provider, { value: ThemeFactory.create({ calendarBottomSeparatorBorder: 'none' }, theme) },
                React.createElement(CommonWrapper, __assign({ rootNodeRef: _this.setRootNode }, _this.getProps()), _this.renderMain)));
        }));
    };
    DatePicker.prototype.parseValueToDate = function (value) {
        if (value === undefined || value === null) {
            return undefined;
        }
        var date = new InternalDate({ value: value });
        if (date.validate({ checks: [InternalDateValidateCheck.NotNull, InternalDateValidateCheck.Native] })) {
            return date.toString({ withPad: true });
        }
        return undefined;
    };
    DatePicker.prototype.renderTodayLink = function () {
        var _this = this;
        var _a = this.locale, order = _a.order, separator = _a.separator;
        var today = new InternalDate({ order: order, separator: separator })
            .setComponents(InternalDateGetter.getTodayComponents())
            .toString({ withPad: true, withSeparator: true });
        return (React.createElement("div", { style: { margin: 8 } },
            React.createElement(Button, { "aria-label": this.locale.todayAriaLabel, "data-tid": DatePickerDataTids.pickerTodayWrapper, width: "100%", onClick: function () {
                    _this.handleSelect(today);
                }, icon: React.createElement(ArrowAUpIcon16Light, null) }, this.locale.today)));
    };
    var DatePicker_1;
    DatePicker.__KONTUR_REACT_UI__ = 'DatePicker';
    DatePicker.displayName = 'DatePicker';
    DatePicker.defaultProps = {
        minDate: MIN_FULLDATE,
        maxDate: MAX_FULLDATE,
    };
    DatePicker.validate = function (value, range) {
        if (range === void 0) { range = {}; }
        if (!value) {
            return false;
        }
        var _a = range.minDate, minDate = _a === void 0 ? MIN_FULLDATE : _a, _b = range.maxDate, maxDate = _b === void 0 ? MAX_FULLDATE : _b;
        var internalDate = new InternalDate({
            order: InternalDateOrder.DMY,
            separator: InternalDateSeparator.Dot,
        })
            .setRangeStart(new InternalDate({ value: minDate }))
            .setRangeEnd(new InternalDate({ value: maxDate }))
            .parseValue(value);
        return internalDate.validate({
            checks: [
                InternalDateValidateCheck.NotNull,
                InternalDateValidateCheck.Number,
                InternalDateValidateCheck.Native,
                InternalDateValidateCheck.Limits,
                InternalDateValidateCheck.Range,
            ],
        });
    };
    DatePicker = DatePicker_1 = __decorate([
        withRenderEnvironment,
        responsiveLayout,
        rootNode,
        locale('DatePicker', DatePickerLocaleHelper)
    ], DatePicker);
    return DatePicker;
}(React.PureComponent));
export { DatePicker };
//# sourceMappingURL=DatePicker.js.map