/**
 * DevExtreme (esm/ui/text_box/ui.text_editor.mask.strategy.js)
 * Version: 23.1.6 (build 23316-0110)
 * Build date: Sun Nov 12 2023
 *
 * Copyright (c) 2012 - 2023 Developer Express Inc. ALL RIGHTS RESERVED
 * Read about DevExtreme licensing here: https://js.devexpress.com/Licensing/
 */
import EventsEngine from "../../events/core/events_engine";
import {
    addNamespace
} from "../../events/utils/index";
import browser from "../../core/utils/browser";
import {
    clipboardText as getClipboardText
} from "../../core/utils/dom";
var MASK_EVENT_NAMESPACE = "dxMask";
var BLUR_EVENT = "blur beforedeactivate";
var EMPTY_CHAR = " ";
var DELETE_INPUT_TYPES = ["deleteContentBackward", "deleteSoftLineBackward", "deleteContent", "deleteHardLineBackward"];
var HISTORY_INPUT_TYPES = ["historyUndo", "historyRedo"];
var EVENT_NAMES = ["focusIn", "focusOut", "input", "paste", "cut", "drop", "beforeInput"];

function getEmptyString(length) {
    return EMPTY_CHAR.repeat(length)
}
export default class MaskStrategy {
    constructor(editor) {
        this.editor = editor
    }
    _editorOption() {
        return this.editor.option(...arguments)
    }
    _editorInput() {
        return this.editor._input()
    }
    _editorCaret(newCaret) {
        if (!newCaret) {
            return this.editor._caret()
        }
        this.editor._caret(newCaret)
    }
    _attachChangeEventHandler() {
        if (!this._editorOption("valueChangeEvent").split(" ").includes("change")) {
            return
        }
        var $input = this._editorInput();
        var namespace = addNamespace(BLUR_EVENT, MASK_EVENT_NAMESPACE);
        EventsEngine.on($input, namespace, e => {
            this.editor._changeHandler(e)
        })
    }
    _beforeInputHandler() {
        this._previousText = this._editorOption("text");
        this._prevCaret = this._editorCaret()
    }
    _inputHandler(event) {
        var {
            originalEvent: originalEvent
        } = event;
        if (!originalEvent) {
            return
        }
        var {
            inputType: inputType
        } = originalEvent;
        if (HISTORY_INPUT_TYPES.includes(inputType)) {
            this._handleHistoryInputEvent()
        } else if (DELETE_INPUT_TYPES.includes(inputType)) {
            this._handleBackwardDeleteInputEvent()
        } else {
            var currentCaret = this._editorCaret();
            if (!currentCaret.end) {
                return
            }
            this._clearSelectedText();
            this._autoFillHandler(originalEvent);
            this._editorCaret(currentCaret);
            this._handleInsertTextInputEvent(originalEvent.data)
        }
        if (this._editorOption("text") === this._previousText) {
            event.stopImmediatePropagation()
        }
    }
    _handleHistoryInputEvent() {
        var caret = this._editorCaret();
        this._updateEditorMask({
            start: caret.start,
            length: caret.end - caret.start,
            text: ""
        });
        this._editorCaret(this._prevCaret)
    }
    _handleBackwardDeleteInputEvent() {
        this._clearSelectedText();
        var caret = this._editorCaret();
        this.editor.setForwardDirection();
        this.editor._adjustCaret();
        var adjustedForwardCaret = this._editorCaret();
        if (adjustedForwardCaret.start !== caret.start) {
            this.editor.setBackwardDirection();
            this.editor._adjustCaret()
        }
    }
    _clearSelectedText() {
        var _this$_prevCaret, _this$_prevCaret2;
        var length = (null === (_this$_prevCaret = this._prevCaret) || void 0 === _this$_prevCaret ? void 0 : _this$_prevCaret.end) - (null === (_this$_prevCaret2 = this._prevCaret) || void 0 === _this$_prevCaret2 ? void 0 : _this$_prevCaret2.start) || 1;
        var caret = this._editorCaret();
        if (!this._isAutoFill()) {
            this.editor.setBackwardDirection();
            this._updateEditorMask({
                start: caret.start,
                length: length,
                text: getEmptyString(length)
            })
        }
    }
    _handleInsertTextInputEvent(data) {
        var _this$_prevCaret$star, _this$_prevCaret3;
        var text = null !== data && void 0 !== data ? data : "";
        this.editor.setForwardDirection();
        var hasValidChars = this._updateEditorMask({
            start: null !== (_this$_prevCaret$star = null === (_this$_prevCaret3 = this._prevCaret) || void 0 === _this$_prevCaret3 ? void 0 : _this$_prevCaret3.start) && void 0 !== _this$_prevCaret$star ? _this$_prevCaret$star : 0,
            length: text.length || 1,
            text: text
        });
        if (!hasValidChars) {
            this._editorCaret(this._prevCaret)
        }
    }
    _updateEditorMask(args) {
        var textLength = args.text.length;
        var processedCharsCount = this.editor._handleChain(args);
        this.editor._displayMask();
        if (this.editor.isForwardDirection()) {
            var {
                start: start,
                end: end
            } = this._editorCaret();
            var correction = processedCharsCount - textLength;
            var hasSkippedStub = processedCharsCount > 1;
            if (hasSkippedStub && 1 === textLength) {
                this._editorCaret({
                    start: start + correction,
                    end: end + correction
                })
            }
            this.editor._adjustCaret()
        }
        return !!processedCharsCount
    }
    _focusInHandler() {
        this.editor._showMaskPlaceholder();
        this.editor.setForwardDirection();
        if (!this.editor._isValueEmpty() && this._editorOption("isValid")) {
            this.editor._adjustCaret()
        } else {
            var caret = this.editor._maskRulesChain.first();
            this._caretTimeout = setTimeout(() => {
                this._editorCaret({
                    start: caret,
                    end: caret
                })
            }, 0)
        }
    }
    _focusOutHandler(event) {
        this.editor._changeHandler(event);
        if ("onFocus" === this._editorOption("showMaskMode") && this.editor._isValueEmpty()) {
            this._editorOption("text", "");
            this.editor._renderDisplayText("")
        }
    }
    _delHandler(event) {
        var {
            editor: editor
        } = this;
        editor._maskKeyHandler(event, () => {
            if (!editor._hasSelection()) {
                editor._handleKey(EMPTY_CHAR)
            }
        })
    }
    _cutHandler(event) {
        var caret = this._editorCaret();
        var selectedText = this._editorInput().val().substring(caret.start, caret.end);
        this.editor._maskKeyHandler(event, () => getClipboardText(event, selectedText))
    }
    _dropHandler() {
        this._clearDragTimer();
        this._dragTimer = setTimeout(() => {
            var value = this.editor._convertToValue(this._editorInput().val());
            this._editorOption("value", value)
        })
    }
    _pasteHandler(event) {
        var {
            editor: editor
        } = this;
        if (this._editorOption("disabled")) {
            return
        }
        var caret = this._editorCaret();
        editor._maskKeyHandler(event, () => {
            var pastedText = getClipboardText(event);
            var restText = editor._maskRulesChain.text().substring(caret.end);
            var accepted = editor._handleChain({
                text: pastedText,
                start: caret.start,
                length: pastedText.length
            });
            var newCaret = caret.start + accepted;
            editor._handleChain({
                text: restText,
                start: newCaret,
                length: restText.length
            });
            editor._caret({
                start: newCaret,
                end: newCaret
            })
        })
    }
    _autoFillHandler(event) {
        var {
            editor: editor
        } = this;
        var inputVal = this._editorInput().val();
        this._inputHandlerTimer = setTimeout(() => {
            if (this._isAutoFill()) {
                editor._maskKeyHandler(event, () => {
                    editor._handleChain({
                        text: inputVal,
                        start: 0,
                        length: inputVal.length
                    })
                });
                editor._validateMask()
            }
        })
    }
    _isAutoFill() {
        var $input = this._editorInput();
        if (browser.webkit) {
            var _input$matches;
            var input = $input.get(0);
            return null !== (_input$matches = null === input || void 0 === input ? void 0 : input.matches(":-webkit-autofill")) && void 0 !== _input$matches ? _input$matches : false
        }
        return false
    }
    _clearDragTimer() {
        clearTimeout(this._dragTimer)
    }
    getHandler(handlerName) {
        return args => {
            var _this;
            null === (_this = this["_".concat(handlerName, "Handler")]) || void 0 === _this ? void 0 : _this.call(this, args)
        }
    }
    attachEvents() {
        var $input = this._editorInput();
        EVENT_NAMES.forEach(eventName => {
            var namespace = addNamespace(eventName.toLowerCase(), MASK_EVENT_NAMESPACE);
            EventsEngine.on($input, namespace, this.getHandler(eventName))
        });
        this._attachChangeEventHandler()
    }
    detachEvents() {
        EventsEngine.off(this._editorInput(), ".".concat(MASK_EVENT_NAMESPACE))
    }
    clean() {
        this._clearDragTimer();
        clearTimeout(this._caretTimeout);
        clearTimeout(this._inputHandlerTimer)
    }
}
