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 ReactDOM from 'react-dom';
import { ConditionalHandler } from '../../lib/ConditionalHandler.js';
import { LENGTH_FULLDATE, MAX_FULLDATE, MIN_FULLDATE } from '../../lib/date/constants.js';
import { InternalDateComponentType } from '../../lib/date/types.js';
import { DatePickerLocaleHelper } from '../DatePicker/locale/index.js';
import { InputLikeText } from '../../internal/InputLikeText/index.js';
import { locale } from '../../lib/locale/decorators.js';
import { ThemeContext } from '../../lib/theming/ThemeContext.js';
import { CommonWrapper } from '../../internal/CommonWrapper/index.js';
import { rootNode } from '../../lib/rootNode/index.js';
import { createPropsGetter } from '../../lib/createPropsGetter.js';
import { FocusControlWrapper } from '../../internal/FocusControlWrapper/index.js';
import { withSize } from '../../lib/size/SizeDecorator.js';
import { withRenderEnvironment } from '../../lib/renderEnvironment/index.js';
import { CalendarIcon } from './CalendarIcon.js';
import { DateFragmentsView } from './DateFragmentsView.js';
import { getStyles } from './DateInput.styles.js';
import { Actions, extractAction } from './helpers/DateInputKeyboardActions.js';
import { InternalDateMediator } from './helpers/InternalDateMediator.js';
export var DateInputDataTids = {
    root: 'DateInput__root',
    icon: 'DateInput__icon',
};
/**
 * Компонент поля `DateInput` из DatePicker'а помогает выбирать дату с клавиатуры.
 */
var DateInput = /** @class */ (function (_super) {
    __extends(DateInput, _super);
    function DateInput(props) {
        var _this = _super.call(this, props) || this;
        _this.getProps = createPropsGetter(DateInput_1.defaultProps);
        _this.iDateMediator = new InternalDateMediator();
        _this.inputLikeText = null;
        _this.dateFragmentsView = null;
        _this.isMouseDown = false;
        _this.isMouseFocus = false;
        _this.ignoringDelimiter = false;
        _this.blurEvent = null;
        _this.conditionalHandler = new ConditionalHandler()
            .add(Actions.MoveSelectionLeft, function () { return _this.shiftSelection(-1); })
            .add(Actions.MoveSelectionRight, function () { return _this.shiftSelection(1); })
            .add(Actions.Separator, function () { return _this.pressDelimiter(); })
            .add(Actions.MoveSelectionFirst, function () { return _this.selectDateComponent(_this.iDateMediator.getLeftmostType()); })
            .add(Actions.MoveSelectionLast, function () { return _this.selectDateComponent(_this.iDateMediator.getRightmostType()); })
            .add(Actions.Increment, function () { return _this.shiftDateComponent(1); })
            .add(Actions.Decrement, function () { return _this.shiftDateComponent(-1); })
            .add(Actions.Digit, function (e) { return _this.inputValue(e); })
            .add(Actions.ClearSelection, function () { return _this.clearSelected(); })
            .add(Actions.ClearOneChar, function () { return _this.clearOneChar(); })
            .add(Actions.FullSelection, function () { return _this.fullSelection(); })
            .add(Actions.WrongInput, function () { return _this.blink(); })
            .build();
        _this.selectNode = function () {
            var type = _this.state.selected;
            var dateFragmentsView = _this.dateFragmentsView && _this.dateFragmentsView.getRootNode();
            if (type === null || !_this.inputLikeText || !dateFragmentsView) {
                return;
            }
            if (type === InternalDateComponentType.All) {
                _this.inputLikeText.selectInnerNode(dateFragmentsView, 0, 5);
                return;
            }
            var index = _this.iDateMediator.getTypesOrder().indexOf(type);
            if (index > -1) {
                _this.inputLikeText.selectInnerNode(dateFragmentsView, index * 2, index * 2 + 1);
            }
        };
        _this.renderIcon = function () {
            var _a;
            var _b = _this.props, withIcon = _b.withIcon, _c = _b.disabled, disabled = _c === void 0 ? false : _c;
            var size = _this.size;
            if (withIcon) {
                var theme = _this.theme;
                var icon = React.createElement(CalendarIcon, { size: size });
                var iconStyles = _this.cx((_a = {},
                    _a[_this.styles.icon(theme)] = true,
                    _a[_this.styles.iconSmall(theme)] = size === 'small',
                    _a[_this.styles.iconMedium(theme)] = size === 'medium',
                    _a[_this.styles.iconLarge(theme)] = size === 'large',
                    _a[_this.styles.iconDisabled(theme)] = disabled,
                    _a));
                return (React.createElement("span", { className: iconStyles, "data-tid": DateInputDataTids.icon }, icon));
            }
            return null;
        };
        _this.handleFocus = function (e) {
            _this.setState(function (prevState) { return ({
                focused: true,
                selected: _this.isMouseDown && !prevState.focused ? prevState.selected : _this.iDateMediator.getLeftmostType(),
            }); });
            if (_this.props.onFocus) {
                _this.props.onFocus(e);
            }
        };
        _this.resetFocus = function () { return _this.updateValue({ focused: false, selected: null, inputMode: false }, false); };
        _this.handleBlur = function (e) {
            _this.resetFocus();
            if (_this.props.onBlur) {
                var restored = _this.iDateMediator.restore();
                if (restored) {
                    e.persist();
                    _this.blurEvent = e;
                }
                else {
                    _this.props.onBlur(e);
                }
            }
        };
        _this.handleMouseDownCapture = function (e) {
            var isFragment = _this.dateFragmentsView ? _this.dateFragmentsView.isFragment(e.target) : false;
            if (_this.state.focused && !isFragment) {
                e.preventDefault();
            }
            _this.isMouseFocus = !_this.state.focused;
            _this.isMouseDown = isFragment;
        };
        _this.handleSelectDateComponent = function (type) {
            if (!(_this.isMouseFocus && _this.iDateMediator.isEmpty())) {
                _this.selectDateComponent(type);
            }
            _this.isMouseFocus = false;
            _this.isMouseDown = false;
        };
        _this.handleMouseDragStart = function () {
            _this.setState({ dragged: true, selected: null });
        };
        _this.handleMouseDragEnd = function () {
            var _a, _b;
            var selection = (_b = (_a = _this.globalObject).getSelection) === null || _b === void 0 ? void 0 : _b.call(_a);
            if (selection &&
                selection.toString().length === LENGTH_FULLDATE &&
                _this.state.selected !== InternalDateComponentType.All) {
                _this.selectDateComponent(InternalDateComponentType.All);
            }
        };
        _this.handleKeyDown = function (e) {
            if (_this.conditionalHandler(extractAction(e), e)) {
                e.preventDefault();
            }
            if (_this.props.onKeyDown) {
                _this.props.onKeyDown(e);
            }
        };
        _this.handlePaste = function (e) {
            var pasted = e && e.clipboardData.getData('text').trim();
            if (pasted && _this.iDateMediator.validateString(pasted)) {
                _this.iDateMediator.paste(pasted);
                _this.updateValue();
            }
        };
        _this.handleDoubleClick = function () {
            _this.selectDateComponent(InternalDateComponentType.All);
        };
        _this.inputLikeTextRef = function (el) {
            _this.inputLikeText = el;
        };
        _this.dateFragmentsViewRef = function (el) {
            _this.dateFragmentsView = el;
        };
        _this.selectDateComponent = function (selected) {
            _this.setState({ selected: selected, inputMode: false });
        };
        _this.updateValue = function (state, sync) {
            if (state === void 0) { state = {}; }
            if (sync === void 0) { sync = true; }
            var valueFormatted = _this.iDateMediator.getString();
            var update = function () { return _this.setState(__assign(__assign({}, state), { valueFormatted: valueFormatted }), _this.emitChange); };
            if (sync && Number(React.version) >= 18) {
                ReactDOM.flushSync(update);
            }
            else {
                update();
            }
        };
        _this.updateFromProps = function (sync) {
            _this.iDateMediator.update(_this.props, _this.locale);
            _this.updateValue({}, sync);
        };
        _this.fullSelection = function () {
            _this.selectDateComponent(InternalDateComponentType.All);
        };
        _this.pressDelimiter = function () {
            var value = _this.iDateMediator.get(_this.state.selected);
            if (value !== null && value !== '') {
                if (!_this.ignoringDelimiter) {
                    _this.shiftSelection(1);
                }
                _this.ignoringDelimiter = false;
            }
        };
        _this.emitChange = function () {
            if (_this.props.onValueChange) {
                var value = _this.iDateMediator.getInternalString();
                if (_this.props.value !== value) {
                    _this.props.onValueChange(value);
                }
            }
            // `this.blurEvent` is always null in `flushSync` without `setTimeout` due to sync update
            setTimeout(function () {
                if (_this.blurEvent && _this.props.onBlur) {
                    _this.props.onBlur(_this.blurEvent);
                    _this.blurEvent = null;
                }
            });
        };
        _this.clearSelected = function () {
            var selected = _this.state.selected === null ? _this.iDateMediator.getLeftmostType() : _this.state.selected;
            _this.iDateMediator.clear(selected);
            _this.updateValue({
                inputMode: false,
                selected: selected === InternalDateComponentType.All ? _this.iDateMediator.getLeftmostType() : selected,
            });
        };
        _this.clearOneChar = function () {
            var _a = _this.state, selected = _a.selected, inputMode = _a.inputMode;
            var nextType = selected === null ? _this.iDateMediator.getRightmostType() : selected;
            if (_this.iDateMediator.isNull(nextType)) {
                _this.shiftSelection(-1);
                return;
            }
            if (selected === InternalDateComponentType.All) {
                _this.iDateMediator.clear(InternalDateComponentType.All);
                _this.updateValue({ selected: _this.iDateMediator.getLeftmostType() });
                return;
            }
            _this.iDateMediator.deleteOneCharRight(nextType, inputMode);
            _this.updateValue({
                inputMode: _this.iDateMediator.get(nextType) !== null,
                selected: nextType,
            });
        };
        _this.shiftDateComponent = function (step) {
            var selected = _this.state.selected;
            var changed = _this.iDateMediator.shiftDateComponent(selected, step);
            if (!changed) {
                _this.blink();
                return;
            }
            _this.updateValue({
                inputMode: false,
                selected: selected === InternalDateComponentType.All ? _this.iDateMediator.getLeftmostType() : selected,
            });
        };
        _this.shiftSelection = function (step) {
            var selected = _this.iDateMediator.getShiftedType(_this.state.selected, step);
            if (selected !== _this.state.selected) {
                _this.setState({ selected: selected, inputMode: false });
            }
        };
        _this.inputValue = function (event) {
            var selected = _this.state.selected;
            if (selected === InternalDateComponentType.All) {
                selected = _this.iDateMediator.getLeftmostType();
                _this.iDateMediator.clear(InternalDateComponentType.All);
                _this.setState({ selected: selected });
            }
            var inputMode = _this.iDateMediator.inputKey(event.key, selected, _this.state.inputMode).inputMode;
            if (!inputMode) {
                _this.ignoringDelimiter = true;
                _this.shiftSelection(1);
            }
            _this.updateValue({ inputMode: inputMode });
        };
        _this.state = {
            valueFormatted: '',
            selected: null,
            inputMode: false,
            focused: false,
            dragged: false,
        };
        return _this;
    }
    DateInput_1 = DateInput;
    DateInput.prototype.componentDidUpdate = function (prevProps) {
        var _a = this.getProps(), value = _a.value, minDate = _a.minDate, maxDate = _a.maxDate;
        if (prevProps.value !== value ||
            prevProps.minDate !== minDate ||
            prevProps.maxDate !== maxDate ||
            this.iDateMediator.isChangedLocale(this.locale)) {
            this.updateFromProps(false);
        }
        !this.props.disabled && this.selectNode();
    };
    DateInput.prototype.componentDidMount = function () {
        this.updateFromProps(false);
        if (this.props.autoFocus) {
            this.focus();
        }
    };
    DateInput.prototype.blur = function () {
        if (this.inputLikeText) {
            this.inputLikeText.blur();
        }
    };
    DateInput.prototype.focus = function () {
        if (this.inputLikeText) {
            this.inputLikeText.focus();
        }
    };
    DateInput.prototype.blink = function () {
        if (this.inputLikeText) {
            this.inputLikeText.blink();
        }
    };
    DateInput.prototype.render = function () {
        var _this = this;
        this.styles = getStyles(this.emotion);
        return (React.createElement(ThemeContext.Consumer, null, function (theme) {
            _this.theme = theme;
            return _this.renderMain();
        }));
    };
    DateInput.prototype.renderMain = function () {
        var _a;
        var _b = this.state, focused = _b.focused, selected = _b.selected, inputMode = _b.inputMode, valueFormatted = _b.valueFormatted;
        var showValue = Boolean(focused || valueFormatted);
        var width = this.getProps().width;
        return (React.createElement(CommonWrapper, __assign({ rootNodeRef: this.setRootNode }, this.props),
            React.createElement(FocusControlWrapper, { onBlurWhenDisabled: this.resetFocus },
                React.createElement(InputLikeText, { "data-tid": DateInputDataTids.root, id: this.props.id, width: width, ref: this.inputLikeTextRef, size: this.size, disabled: this.props.disabled, error: this.props.error, warning: this.props.warning, onBlur: this.handleBlur, onFocus: this.handleFocus, onClick: this.props.onClick, onKeyDown: this.handleKeyDown, onMouseDownCapture: this.handleMouseDownCapture, onPaste: this.handlePaste, rightIcon: this.renderIcon(), onDoubleClickCapture: this.handleDoubleClick, onMouseDragStart: this.handleMouseDragStart, onMouseDragEnd: this.handleMouseDragEnd, value: this.iDateMediator.getInternalString(), inputMode: 'numeric', takeContentWidth: true, "aria-describedby": this.props['aria-describedby'], "aria-label": this.props['aria-label'], "aria-labelledby": this.props['aria-labelledby'] },
                    React.createElement("span", { className: this.cx(this.styles.value(), (_a = {}, _a[this.styles.valueVisible()] = showValue, _a)) },
                        React.createElement(DateFragmentsView, { ref: this.dateFragmentsViewRef, fragments: this.iDateMediator.getFragments(), onSelectDateComponent: this.handleSelectDateComponent, selected: selected, inputMode: inputMode }))))));
    };
    var DateInput_1;
    DateInput.__KONTUR_REACT_UI__ = 'DateInput';
    DateInput.displayName = 'DateInput';
    DateInput.defaultProps = {
        value: '',
        minDate: MIN_FULLDATE,
        maxDate: MAX_FULLDATE,
        width: 125,
    };
    DateInput = DateInput_1 = __decorate([
        withRenderEnvironment,
        rootNode,
        locale('DatePicker', DatePickerLocaleHelper),
        withSize
    ], DateInput);
    return DateInput;
}(React.Component));
export { DateInput };
//# sourceMappingURL=DateInput.js.map