import { Host, h } from "@stencil/core";
import { debounceEvent, derivedId, onBoolValueChanged } from '../../utils/utils';
import { NativeValidationStrategy } from '../../utils/native-validation-strategy';
import { DefaultInputController } from './default-input-controller';
let inputId = 0;
export class Input {
    constructor() {
        this.customValidators = [];
        this.controller = new DefaultInputController();
        /**
         * Attributes to be added to the native input such as aria tags
         */
        this.attrs = {};
        /**
         * Indicates whether the value of the control can be automatically completed by the browser. Defaults to `"off"`.
         */
        this.autocomplete = 'off';
        /**
         * Whether autocorrection should be enabled when the user is entering/editing the text value. Defaults to `"off"`.
         */
        this.autocorrect = 'off';
        /**
         * This Boolean attribute lets you specify that a form control should have input focus when the page loads. Defaults to `false`.
         */
        this.autofocus = false;
        /**
         * If true, a clear icon will appear in the input when there is a value. Clicking it clears the input. Defaults to `false`.
         */
        this.clearable = false;
        /**
         * Set the amount of time, in milliseconds, to wait to trigger the `anjChange` event after each keystroke. Default `0`.
         */
        this.debounce = 0;
        /**
         * If true, the user cannot interact with the input. Defaults to `false`.
         */
        this.disabled = false;
        /**
         * The input id
         */
        this.inputId = `anj-input-${inputId++}`;
        /**
         * Id for the label
         */
        this.labelId = derivedId(this.inputId, 'label');
        /**
         * The name of the control, which is submitted with the form data.
         */
        this.name = this.inputId;
        /**
         * If true, the user cannot modify the value. Defaults to `false`.
         */
        this.readonly = false;
        /**
         * If true, the user must fill in a value before submitting a form.
         */
        this.required = false;
        /**
         * If true, the element will have its spelling and grammar checked. Defaults to `false`.
         */
        this.spellcheck = false;
        /**
         * The type of control to display. The default type is text. Possible values are: `"text"`, `"password"`, `"email"`, `"number"`, `"search"`, `"tel"`, or `"url"`.
         */
        this.type = 'text';
        /**
         * The validation strategy to use
         */
        this.validationStrategy = new NativeValidationStrategy();
    }
    get nativeInput() {
        if (!this._nativeInput) {
            this.nativeInput = this.element.querySelector('input');
        }
        return this._nativeInput;
    }
    set nativeInput(input) {
        this._nativeInput = input;
    }
    onContextChanged() {
        this.anjContextChange.emit(this.context);
    }
    debounceChanged() {
        this.anjChange = debounceEvent(this.anjChange, this.debounce);
    }
    invalidChanged(newVal, oldVal) {
        onBoolValueChanged(newVal, oldVal, this.anjInvalid.emit);
    }
    async valueChanged(newVal, oldVal) {
        const valueChanged = await this.controller.hasValueChanged(newVal, oldVal);
        if (!valueChanged) {
            return;
        }
        const value = this.getValue();
        if (this.nativeInput && this.nativeInput.value !== value) {
            this.nativeInput.value = await this.controller.inputFormatter(this.value);
        }
        await this.setInnerValue();
        this.anjChange.emit({ value, innerValue: this.innerValue });
    }
    async componentDidLoad() {
        this.debounceChanged();
        this.value = await this.controller.inputFormatter(this.value);
        this.setInnerValue();
        this.anjControlDidLoad.emit();
    }
    componentWillRender() {
        this.postfix = this.element.querySelector('[slot="end"]');
    }
    componentDidUnload() {
        this.nativeInput = undefined;
        this.anjControlDidUnload.emit();
    }
    async onControlDidLoad({ target }) {
        this.controller = target;
        return this.registerCustomValidator(this.controller.remoteCustomValidator.bind(this.controller));
    }
    /**
     * Focus the native input
     */
    async setFocus() {
        this.nativeInput.focus();
    }
    /**
     * Blur the native input
     */
    async setBlur() {
        this.nativeInput.blur();
    }
    /**
     * Accepts any function, which given the input value, should return a ValidatorResponse
     */
    async registerCustomValidator(validator) {
        this.customValidators.push(validator);
    }
    /**
     * Checks the native element & custom validity
     */
    async checkValidity() {
        this.nativeInput.checkValidity();
        return this.validationStrategy.onValidChange(this.element, this.nativeInput, this.customValidators);
    }
    getValue() {
        return this.value;
    }
    async setInnerValue() {
        this.innerValue = await this.controller.innerValue() || this.value;
    }
    async onInput(event) {
        const input = event.target;
        if (input) {
            this.value = input.value;
        }
        this.anjInput.emit(event);
        if (this.invalid) {
            return this.validationStrategy.onTouched(this.element);
        }
    }
    async onBlur() {
        this.anjBlur.emit();
        this.value = await this.controller.inputFormatter(this.value);
        return this.validationStrategy.onTouched(this.element);
    }
    onFocus() {
        if (!this.readonly) {
            this.anjFocus.emit();
        }
    }
    onClearValue(event) {
        event.preventDefault();
        this.value = '';
    }
    render() {
        const hasPostFix = !!(this.postfix || this.clearable);
        return (h(Host, { "aria-disabled": this.disabled ? 'true' : null, class: { 'anj-has-postfix': hasPostFix } },
            h("slot", { name: "start" }),
            h("input", Object.assign({}, this.attrs, { "aria-labelledby": this.labelId, id: this.inputId, autoComplete: this.autocomplete, autoCorrect: this.autocorrect, autoFocus: this.autofocus, disabled: this.disabled, inputMode: this.inputmode, min: this.min, max: this.max, minLength: this.minlength, maxLength: this.maxlength, multiple: this.multiple, name: this.name, pattern: this.pattern, placeholder: this.placeholder, readOnly: this.readonly, required: this.required, spellCheck: this.spellcheck, step: this.step, size: this.size, type: this.type, value: this.getValue(), ref: ref => this.nativeInput = ref, onInput: (ev) => this.onInput(ev), onBlur: () => this.onBlur(), onFocus: () => this.onFocus(), onInvalid: () => this.validationStrategy.onValidChange(this.element, this.nativeInput, this.customValidators) })),
            (this.clearable && this.getValue() && !this.readonly && !this.disabled)
                ? h("anj-button-close", { slot: "end", context: "clear", free: true, onMouseDown: ev => this.onClearValue(ev) }) : undefined,
            h("slot", { name: "end" }),
            h("slot", null)));
    }
    static get is() { return "anj-input"; }
    static get encapsulation() { return "scoped"; }
    static get originalStyleUrls() { return {
        "$": ["input.scss"]
    }; }
    static get styleUrls() { return {
        "$": ["input.css"]
    }; }
    static get properties() { return {
        "attrs": {
            "type": "unknown",
            "mutable": false,
            "complexType": {
                "original": "{}",
                "resolved": "{}",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": "Attributes to be added to the native input such as aria tags"
            },
            "defaultValue": "{}"
        },
        "autocomplete": {
            "type": "string",
            "mutable": false,
            "complexType": {
                "original": "string",
                "resolved": "string",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": "Indicates whether the value of the control can be automatically completed by the browser. Defaults to `\"off\"`."
            },
            "attribute": "autocomplete",
            "reflect": false,
            "defaultValue": "'off'"
        },
        "autocorrect": {
            "type": "string",
            "mutable": false,
            "complexType": {
                "original": "string",
                "resolved": "string",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": "Whether autocorrection should be enabled when the user is entering/editing the text value. Defaults to `\"off\"`."
            },
            "attribute": "autocorrect",
            "reflect": false,
            "defaultValue": "'off'"
        },
        "autofocus": {
            "type": "boolean",
            "mutable": false,
            "complexType": {
                "original": "boolean",
                "resolved": "boolean",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": "This Boolean attribute lets you specify that a form control should have input focus when the page loads. Defaults to `false`."
            },
            "attribute": "autofocus",
            "reflect": false,
            "defaultValue": "false"
        },
        "clearable": {
            "type": "boolean",
            "mutable": false,
            "complexType": {
                "original": "boolean",
                "resolved": "boolean",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": "If true, a clear icon will appear in the input when there is a value. Clicking it clears the input. Defaults to `false`."
            },
            "attribute": "clearable",
            "reflect": false,
            "defaultValue": "false"
        },
        "context": {
            "type": "string",
            "mutable": false,
            "complexType": {
                "original": "InputContext",
                "resolved": "\"success\" | \"warning\"",
                "references": {
                    "InputContext": {
                        "location": "import",
                        "path": "../../types/types"
                    }
                }
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": "Optional state (to be used sparingly) to provide additional context to the user.\nOptions are `\"success\"`, `\"warning\"`, `undefined`. Default is `undefined`."
            },
            "attribute": "context",
            "reflect": false
        },
        "debounce": {
            "type": "number",
            "mutable": false,
            "complexType": {
                "original": "number",
                "resolved": "number",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": "Set the amount of time, in milliseconds, to wait to trigger the `anjChange` event after each keystroke. Default `0`."
            },
            "attribute": "debounce",
            "reflect": false,
            "defaultValue": "0"
        },
        "disabled": {
            "type": "boolean",
            "mutable": false,
            "complexType": {
                "original": "boolean",
                "resolved": "boolean",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": "If true, the user cannot interact with the input. Defaults to `false`."
            },
            "attribute": "disabled",
            "reflect": true,
            "defaultValue": "false"
        },
        "inputId": {
            "type": "string",
            "mutable": false,
            "complexType": {
                "original": "string",
                "resolved": "string",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": "The input id"
            },
            "attribute": "input-id",
            "reflect": false,
            "defaultValue": "`anj-input-${inputId++}`"
        },
        "inputmode": {
            "type": "string",
            "mutable": false,
            "complexType": {
                "original": "string",
                "resolved": "string",
                "references": {}
            },
            "required": false,
            "optional": true,
            "docs": {
                "tags": [],
                "text": "A hint to the browser for which keyboard to display. This attribute applies when the value of the type attribute is `\"text\"`, `\"password\"`, `\"email\"`, or `\"url\"`. Possible values are: `\"verbatim\"`, `\"latin\"`, `\"latin-name\"`, `\"latin-prose\"`, `\"full-width-latin\"`, `\"kana\"`, `\"katakana\"`, `\"numeric\"`, `\"tel\"`, `\"email\"`, `\"url\"`."
            },
            "attribute": "inputmode",
            "reflect": false
        },
        "invalid": {
            "type": "boolean",
            "mutable": true,
            "complexType": {
                "original": "boolean",
                "resolved": "boolean",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": "Whether the control is valid"
            },
            "attribute": "invalid",
            "reflect": true
        },
        "labelId": {
            "type": "string",
            "mutable": false,
            "complexType": {
                "original": "string",
                "resolved": "string",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": "Id for the label"
            },
            "attribute": "label-id",
            "reflect": false,
            "defaultValue": "derivedId(this.inputId, 'label')"
        },
        "innerValue": {
            "type": "any",
            "mutable": false,
            "complexType": {
                "original": "any",
                "resolved": "any",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": "Exposes the inner value\nShould not be bound to, it is readonly"
            },
            "attribute": "inner-value",
            "reflect": false
        },
        "max": {
            "type": "string",
            "mutable": false,
            "complexType": {
                "original": "string",
                "resolved": "string",
                "references": {}
            },
            "required": false,
            "optional": true,
            "docs": {
                "tags": [],
                "text": "The maximum value, which must not be less than its minimum (min attribute) value."
            },
            "attribute": "max",
            "reflect": false
        },
        "maxlength": {
            "type": "number",
            "mutable": false,
            "complexType": {
                "original": "number",
                "resolved": "number",
                "references": {}
            },
            "required": false,
            "optional": true,
            "docs": {
                "tags": [],
                "text": "If the value of the type attribute is `text`, `email`, `search`, `password`, `tel`, or `url`, this attribute specifies the maximum number of characters that the user can enter."
            },
            "attribute": "maxlength",
            "reflect": false
        },
        "min": {
            "type": "string",
            "mutable": false,
            "complexType": {
                "original": "string",
                "resolved": "string",
                "references": {}
            },
            "required": false,
            "optional": true,
            "docs": {
                "tags": [],
                "text": "The minimum value, which must not be greater than its maximum (max attribute) value."
            },
            "attribute": "min",
            "reflect": false
        },
        "minlength": {
            "type": "number",
            "mutable": false,
            "complexType": {
                "original": "number",
                "resolved": "number",
                "references": {}
            },
            "required": false,
            "optional": true,
            "docs": {
                "tags": [],
                "text": "If the value of the type attribute is `text`, `email`, `search`, `password`, `tel`, or `url`, this attribute specifies the minimum number of characters that the user can enter."
            },
            "attribute": "minlength",
            "reflect": false
        },
        "multiple": {
            "type": "boolean",
            "mutable": false,
            "complexType": {
                "original": "boolean",
                "resolved": "boolean",
                "references": {}
            },
            "required": false,
            "optional": true,
            "docs": {
                "tags": [],
                "text": "If true, the user can enter more than one value. This attribute applies when the type attribute is set to `\"email\"` or `\"file\"`, otherwise it is ignored."
            },
            "attribute": "multiple",
            "reflect": false
        },
        "name": {
            "type": "string",
            "mutable": false,
            "complexType": {
                "original": "string",
                "resolved": "string",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": "The name of the control, which is submitted with the form data."
            },
            "attribute": "name",
            "reflect": false,
            "defaultValue": "this.inputId"
        },
        "pattern": {
            "type": "string",
            "mutable": false,
            "complexType": {
                "original": "string",
                "resolved": "string",
                "references": {}
            },
            "required": false,
            "optional": true,
            "docs": {
                "tags": [],
                "text": "A regular expression that the value is checked against. The pattern must match the entire value, not just some subset. Use the title attribute to describe the pattern to help the user. This attribute applies when the value of the type attribute is `\"text\"`, `\"search\"`, `\"tel\"`, `\"url\"`, `\"email\"`, or `\"password\"`, otherwise it is ignored."
            },
            "attribute": "pattern",
            "reflect": false
        },
        "placeholder": {
            "type": "string",
            "mutable": false,
            "complexType": {
                "original": "string",
                "resolved": "string",
                "references": {}
            },
            "required": false,
            "optional": true,
            "docs": {
                "tags": [],
                "text": "Instructional text that shows before the input has a value."
            },
            "attribute": "placeholder",
            "reflect": false
        },
        "readonly": {
            "type": "boolean",
            "mutable": false,
            "complexType": {
                "original": "boolean",
                "resolved": "boolean",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": "If true, the user cannot modify the value. Defaults to `false`."
            },
            "attribute": "readonly",
            "reflect": true,
            "defaultValue": "false"
        },
        "required": {
            "type": "boolean",
            "mutable": false,
            "complexType": {
                "original": "boolean",
                "resolved": "boolean",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": "If true, the user must fill in a value before submitting a form."
            },
            "attribute": "required",
            "reflect": false,
            "defaultValue": "false"
        },
        "spellcheck": {
            "type": "boolean",
            "mutable": false,
            "complexType": {
                "original": "boolean",
                "resolved": "boolean",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": "If true, the element will have its spelling and grammar checked. Defaults to `false`."
            },
            "attribute": "spellcheck",
            "reflect": false,
            "defaultValue": "false"
        },
        "step": {
            "type": "string",
            "mutable": false,
            "complexType": {
                "original": "string",
                "resolved": "string",
                "references": {}
            },
            "required": false,
            "optional": true,
            "docs": {
                "tags": [],
                "text": "Works with the min and max attributes to limit the increments at which a value can be set. Possible values are: `\"any\"` or a positive floating point number."
            },
            "attribute": "step",
            "reflect": false
        },
        "size": {
            "type": "number",
            "mutable": false,
            "complexType": {
                "original": "number",
                "resolved": "number",
                "references": {}
            },
            "required": false,
            "optional": true,
            "docs": {
                "tags": [],
                "text": "The initial size of the control. This value is in pixels unless the value of the type attribute is `\"text\"` or `\"password\"`, in which case it is an integer number of characters. This attribute applies only when the `type` attribute is set to `\"text\"`, `\"search\"`, `\"tel\"`, `\"url\"`, `\"email\"`, or `\"password\"`, otherwise it is ignored."
            },
            "attribute": "size",
            "reflect": false
        },
        "type": {
            "type": "string",
            "mutable": false,
            "complexType": {
                "original": "InputControlType",
                "resolved": "\"email\" | \"number\" | \"password\" | \"search\" | \"tel\" | \"text\" | \"url\"",
                "references": {
                    "InputControlType": {
                        "location": "import",
                        "path": "../../types/types"
                    }
                }
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": "The type of control to display. The default type is text. Possible values are: `\"text\"`, `\"password\"`, `\"email\"`, `\"number\"`, `\"search\"`, `\"tel\"`, or `\"url\"`."
            },
            "attribute": "type",
            "reflect": false,
            "defaultValue": "'text'"
        },
        "validationStrategy": {
            "type": "unknown",
            "mutable": false,
            "complexType": {
                "original": "NativeValidationStrategy",
                "resolved": "NativeValidationStrategy",
                "references": {
                    "NativeValidationStrategy": {
                        "location": "import",
                        "path": "../../utils/native-validation-strategy"
                    }
                }
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": "The validation strategy to use"
            },
            "defaultValue": "new NativeValidationStrategy()"
        },
        "value": {
            "type": "any",
            "mutable": true,
            "complexType": {
                "original": "string | number",
                "resolved": "number | string",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": "The value of the input."
            },
            "attribute": "value",
            "reflect": false
        }
    }; }
    static get states() { return {
        "postfix": {}
    }; }
    static get events() { return [{
            "method": "anjInvalid",
            "name": "anjInvalid",
            "bubbles": true,
            "cancelable": true,
            "composed": true,
            "docs": {
                "tags": [],
                "text": "Emitted when invalid status changes."
            },
            "complexType": {
                "original": "boolean",
                "resolved": "boolean",
                "references": {}
            }
        }, {
            "method": "anjInput",
            "name": "anjInput",
            "bubbles": true,
            "cancelable": true,
            "composed": true,
            "docs": {
                "tags": [],
                "text": "Emitted when a keyboard input ocurred."
            },
            "complexType": {
                "original": "any",
                "resolved": "any",
                "references": {}
            }
        }, {
            "method": "anjContextChange",
            "name": "anjContextChange",
            "bubbles": true,
            "cancelable": true,
            "composed": true,
            "docs": {
                "tags": [],
                "text": "Emitted when the input context changes."
            },
            "complexType": {
                "original": "InputContext",
                "resolved": "\"success\" | \"warning\"",
                "references": {
                    "InputContext": {
                        "location": "import",
                        "path": "../../types/types"
                    }
                }
            }
        }, {
            "method": "anjChange",
            "name": "anjChange",
            "bubbles": true,
            "cancelable": true,
            "composed": true,
            "docs": {
                "tags": [],
                "text": "Emitted when the value has changed."
            },
            "complexType": {
                "original": "InputChangeEvent",
                "resolved": "InputChangeEvent",
                "references": {
                    "InputChangeEvent": {
                        "location": "import",
                        "path": "../../types/types"
                    }
                }
            }
        }, {
            "method": "anjBlur",
            "name": "anjBlur",
            "bubbles": true,
            "cancelable": true,
            "composed": true,
            "docs": {
                "tags": [],
                "text": "Emitted when the input loses focus."
            },
            "complexType": {
                "original": "void",
                "resolved": "void",
                "references": {}
            }
        }, {
            "method": "anjFocus",
            "name": "anjFocus",
            "bubbles": true,
            "cancelable": true,
            "composed": true,
            "docs": {
                "tags": [],
                "text": "Emitted when the input has focus."
            },
            "complexType": {
                "original": "void",
                "resolved": "void",
                "references": {}
            }
        }, {
            "method": "anjControlDidLoad",
            "name": "anjControlDidLoad",
            "bubbles": true,
            "cancelable": true,
            "composed": true,
            "docs": {
                "tags": [],
                "text": "Emitted when the input has been created."
            },
            "complexType": {
                "original": "void",
                "resolved": "void",
                "references": {}
            }
        }, {
            "method": "anjControlDidUnload",
            "name": "anjControlDidUnload",
            "bubbles": true,
            "cancelable": true,
            "composed": true,
            "docs": {
                "tags": [],
                "text": "Emitted when the input has been removed."
            },
            "complexType": {
                "original": "void",
                "resolved": "void",
                "references": {}
            }
        }]; }
    static get methods() { return {
        "setFocus": {
            "complexType": {
                "signature": "() => Promise<void>",
                "parameters": [],
                "references": {
                    "Promise": {
                        "location": "global"
                    }
                },
                "return": "Promise<void>"
            },
            "docs": {
                "text": "Focus the native input",
                "tags": []
            }
        },
        "setBlur": {
            "complexType": {
                "signature": "() => Promise<void>",
                "parameters": [],
                "references": {
                    "Promise": {
                        "location": "global"
                    }
                },
                "return": "Promise<void>"
            },
            "docs": {
                "text": "Blur the native input",
                "tags": []
            }
        },
        "registerCustomValidator": {
            "complexType": {
                "signature": "(validator: CustomValidatorFn) => Promise<void>",
                "parameters": [{
                        "tags": [],
                        "text": ""
                    }],
                "references": {
                    "Promise": {
                        "location": "global"
                    },
                    "CustomValidatorFn": {
                        "location": "import",
                        "path": "../../types/types"
                    }
                },
                "return": "Promise<void>"
            },
            "docs": {
                "text": "Accepts any function, which given the input value, should return a ValidatorResponse",
                "tags": []
            }
        },
        "checkValidity": {
            "complexType": {
                "signature": "() => Promise<boolean>",
                "parameters": [],
                "references": {
                    "Promise": {
                        "location": "global"
                    }
                },
                "return": "Promise<boolean>"
            },
            "docs": {
                "text": "Checks the native element & custom validity",
                "tags": []
            }
        }
    }; }
    static get elementRef() { return "element"; }
    static get watchers() { return [{
            "propName": "context",
            "methodName": "onContextChanged"
        }, {
            "propName": "debounce",
            "methodName": "debounceChanged"
        }, {
            "propName": "invalid",
            "methodName": "invalidChanged"
        }, {
            "propName": "value",
            "methodName": "valueChanged"
        }]; }
    static get listeners() { return [{
            "name": "anjInputControlDidLoad",
            "method": "onControlDidLoad",
            "target": undefined,
            "capture": false,
            "passive": false
        }]; }
}
