"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "ConditionComponent", {
    enumerable: true,
    get: function() {
        return ConditionComponent;
    }
});
const _element = require("../../../helpers/dom/element");
const _event = require("../../../helpers/dom/event");
const _array = require("../../../helpers/array");
const _unicode = require("../../../helpers/unicode");
const _object = require("../../../helpers/object");
const _constants = /*#__PURE__*/ _interop_require_wildcard(require("../../../i18n/constants"));
const _base = require("./_base");
const _constants1 = /*#__PURE__*/ _interop_require_wildcard(require("../constants"));
const _input = require("../ui/input");
const _select = require("../ui/select");
const _conditionRegisterer = require("../conditionRegisterer");
function _check_private_redeclaration(obj, privateCollection) {
    if (privateCollection.has(obj)) {
        throw new TypeError("Cannot initialize the same private elements twice on an object");
    }
}
function _class_private_method_get(receiver, privateSet, fn) {
    if (!privateSet.has(receiver)) {
        throw new TypeError("attempted to get private field on non-instance");
    }
    return fn;
}
function _class_private_method_init(obj, privateSet) {
    _check_private_redeclaration(obj, privateSet);
    privateSet.add(obj);
}
function _getRequireWildcardCache(nodeInterop) {
    if (typeof WeakMap !== "function") return null;
    var cacheBabelInterop = new WeakMap();
    var cacheNodeInterop = new WeakMap();
    return (_getRequireWildcardCache = function(nodeInterop) {
        return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
    })(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
    if (!nodeInterop && obj && obj.__esModule) {
        return obj;
    }
    if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
        return {
            default: obj
        };
    }
    var cache = _getRequireWildcardCache(nodeInterop);
    if (cache && cache.has(obj)) {
        return cache.get(obj);
    }
    var newObj = {
        __proto__: null
    };
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for(var key in obj){
        if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
            var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
            if (desc && (desc.get || desc.set)) {
                Object.defineProperty(newObj, key, desc);
            } else {
                newObj[key] = obj[key];
            }
        }
    }
    newObj.default = obj;
    if (cache) {
        cache.set(obj, newObj);
    }
    return newObj;
}
var /**
   * On condition select listener.
   *
   * @param {object} command Menu item object (command).
   */ _onConditionSelect = /*#__PURE__*/ new WeakSet(), /**
   * Key down listener.
   *
   * @param {Event} event The DOM event object.
   */ _onInputKeyDown = /*#__PURE__*/ new WeakSet();
class ConditionComponent extends _base.BaseComponent {
    /**
   * Register all necessary hooks.
   *
   * @private
   */ registerHooks() {
        this.getSelectElement().addLocalHook('select', (command)=>_class_private_method_get(this, _onConditionSelect, onConditionSelect).call(this, command)).addLocalHook('afterClose', ()=>this.runLocalHooks('afterClose')).addLocalHook('tabKeydown', (event)=>this.runLocalHooks('selectTabKeydown', event));
        (0, _array.arrayEach)(this.getInputElements(), (input)=>{
            input.addLocalHook('keydown', (event)=>_class_private_method_get(this, _onInputKeyDown, onInputKeyDown).call(this, event));
        });
    }
    /**
   * Set state of the component.
   *
   * @param {object} value State to restore.
   */ setState(value) {
        this.reset();
        if (!value) {
            return;
        }
        const copyOfCommand = (0, _object.clone)(value.command);
        if (copyOfCommand.name.startsWith(_constants.FILTERS_CONDITIONS_NAMESPACE)) {
            copyOfCommand.name = this.hot.getTranslatedPhrase(copyOfCommand.name);
        }
        this.getSelectElement().setValue(copyOfCommand);
        (0, _array.arrayEach)(value.args, (arg, index)=>{
            if (index > copyOfCommand.inputsCount - 1) {
                return false;
            }
            const element = this.getInputElement(index);
            element.setValue(arg);
            element[copyOfCommand.inputsCount > index ? 'show' : 'hide']();
            if (!index) {
                this.hot._registerTimeout(()=>element.focus(), 10);
            }
        });
    }
    /**
   * Export state of the component (get selected filter and filter arguments).
   *
   * @returns {object} Returns object where `command` key keeps used condition filter and `args` key its arguments.
   */ getState() {
        const command = this.getSelectElement().getValue() || (0, _conditionRegisterer.getConditionDescriptor)(_constants1.CONDITION_NONE);
        const args = [];
        (0, _array.arrayEach)(this.getInputElements(), (element, index)=>{
            if (command.inputsCount > index) {
                args.push(element.getValue());
            }
        });
        return {
            command,
            args
        };
    }
    /**
   * Update state of component.
   *
   * @param {object} condition The condition object.
   * @param {object} condition.command The command object with condition name as `key` property.
   * @param {Array} condition.args An array of values to compare.
   * @param {number} column Physical column index.
   */ updateState(condition, column) {
        const command = condition ? (0, _conditionRegisterer.getConditionDescriptor)(condition.name) : (0, _conditionRegisterer.getConditionDescriptor)(_constants1.CONDITION_NONE);
        this.state.setValueAtIndex(column, {
            command,
            args: condition ? condition.args : []
        });
        if (!condition) {
            (0, _array.arrayEach)(this.getInputElements(), (element)=>element.setValue(null));
        }
    }
    /**
   * Get select element.
   *
   * @returns {SelectUI}
   */ getSelectElement() {
        return this.elements.filter((element)=>element instanceof _select.SelectUI)[0];
    }
    /**
   * Get input element.
   *
   * @param {number} index Index an array of elements.
   * @returns {InputUI}
   */ getInputElement(index = 0) {
        return this.getInputElements()[index];
    }
    /**
   * Get input elements.
   *
   * @returns {Array}
   */ getInputElements() {
        return this.elements.filter((element)=>element instanceof _input.InputUI);
    }
    /**
   * Get menu object descriptor.
   *
   * @returns {object}
   */ getMenuItemDescriptor() {
        return {
            key: this.id,
            name: this.name,
            isCommand: false,
            disableSelection: true,
            hidden: ()=>this.isHidden(),
            renderer: (hot, wrapper, row, col, prop, value)=>{
                (0, _element.addClass)(wrapper.parentNode, 'htFiltersMenuCondition');
                if (this.addSeparator) {
                    (0, _element.addClass)(wrapper.parentNode, 'border');
                }
                const label = this.hot.rootDocument.createElement('div');
                (0, _element.addClass)(label, 'htFiltersMenuLabel');
                label.textContent = value;
                wrapper.appendChild(label);
                // The SelectUI should not extend the menu width (it should adjust to the menu item width only).
                // That's why it's skipped from rendering when the GhostTable tries to render it.
                if (!wrapper.parentElement.hasAttribute('ghost-table')) {
                    (0, _array.arrayEach)(this.elements, (ui)=>wrapper.appendChild(ui.element));
                }
                return wrapper;
            }
        };
    }
    /**
   * Reset elements to their initial state.
   */ reset() {
        const selectedColumn = this.hot.getPlugin('filters').getSelectedColumn();
        let items = [
            (0, _conditionRegisterer.getConditionDescriptor)(_constants1.CONDITION_NONE)
        ];
        if (selectedColumn !== null) {
            const { visualIndex } = selectedColumn;
            items = (0, _constants1.default)(this.hot.getDataType(0, visualIndex, this.hot.countRows(), visualIndex));
        }
        (0, _array.arrayEach)(this.getInputElements(), (element)=>element.hide());
        this.getSelectElement().setItems(items);
        super.reset();
        // Select element as default 'None'
        this.getSelectElement().setValue(items[0]);
    }
    constructor(hotInstance, options){
        super(hotInstance, {
            id: options.id,
            stateless: false
        }), _class_private_method_init(this, _onConditionSelect), _class_private_method_init(this, _onInputKeyDown), /**
   * The name of the component.
   *
   * @type {string}
   */ this.name = '', /**
   * @type {boolean}
   */ this.addSeparator = false;
        this.name = options.name;
        this.addSeparator = options.addSeparator;
        this.elements.push(new _select.SelectUI(this.hot, {
            menuContainer: options.menuContainer
        }));
        this.elements.push(new _input.InputUI(this.hot, {
            placeholder: _constants.FILTERS_BUTTONS_PLACEHOLDER_VALUE
        }));
        this.elements.push(new _input.InputUI(this.hot, {
            placeholder: _constants.FILTERS_BUTTONS_PLACEHOLDER_SECOND_VALUE
        }));
        this.registerHooks();
    }
}
function onConditionSelect(command) {
    (0, _array.arrayEach)(this.getInputElements(), (element, index)=>{
        element[command.inputsCount > index ? 'show' : 'hide']();
        element.options.type = command.inputType ?? 'text';
        if (index === 0) {
            this.hot._registerTimeout(()=>element.focus(), 10);
        }
    });
    this.runLocalHooks('change', command);
}
function onInputKeyDown(event) {
    if ((0, _unicode.isKey)(event.keyCode, 'ESCAPE')) {
        this.runLocalHooks('cancel');
        (0, _event.stopImmediatePropagation)(event);
    }
}
