import { Host, h } from "@stencil/core";
import { cls, getId, isEmpty, prefixFileSize, tinyMDtoHTML } from "../../utils/helpers";
import { Lang } from "../../services/lang";
export class XInputFile {
    constructor() {
        /**
         * Element ID for internal reference
         */
        this.inputId = getId('image');
        this.name = undefined;
        this.placeholder = undefined;
        this.accept = 'image/*';
        this.capture = undefined;
        this.info = undefined;
        this.maxsize = undefined;
        this.maxWidth = undefined;
        this.maxHeight = undefined;
        this.required = undefined;
        this.loading = undefined;
        this.withoutPreview = undefined;
        this.disabled = undefined;
        this.value = null;
        this.isValid = true;
        this.isLoading = undefined;
        this.isDisabled = undefined;
        this.isDragging = undefined;
        this.cropper = undefined;
    }
    /**
     * On value attribute change
     *
     * @param value
     */
    watchValue(value) {
        var _a;
        this.internals.setFormValue(value);
        this.el.dispatchEvent(new InputEvent('change', { bubbles: false }));
        this.el.dispatchEvent(new InputEvent('input', { bubbles: false }));
        this.formValidateCallback(true);
        (_a = this.internals.form) === null || _a === void 0 ? void 0 : _a.dispatchEvent(new InputEvent('input', { bubbles: false }));
        this.onDragLeave();
    }
    /**
     * Element event on slot make changes
     *
     * @param evt
     */
    handleSlotChange() {
        this.computeChildCropper();
    }
    /**
     * Define cropper options
     */
    async setCropperOptions(options) {
        this.cropperOpcions = options;
    }
    /**
     * This is called when the 'disabled' attribute of the element or or an ancestor <fieldset> is updated
     *
     * @param disabled
     */
    formDisabledCallback(disabled) {
        this.isDisabled = disabled;
    }
    /**
     * This is called when the parent/owner form is reset
     */
    formResetCallback() {
        this.isValid = true;
        this.value = null;
    }
    /**
     * This is called when the input is validated
     */
    formValidateCallback(dispatchValidation) {
        if (this.required && isEmpty(this.value)) {
            this.internals.setValidity({ valueMissing: true }, Lang.get('fields.validation.value-missing'));
        }
        else if (this.maxsize && !isEmpty(this.value) && this.value.size > this.maxsize) {
            this.internals.setValidity({ customError: true }, Lang.get('fields.validation.file-too-large', { size: prefixFileSize(this.maxsize) }));
        }
        else if (this.accept && !this.accept.startsWith('image/')) {
            this.internals.setValidity({ typeMismatch: true }, Lang.get('fields.validation.invalid-image-type'));
        }
        else {
            this.internals.setValidity({});
        }
        if (dispatchValidation) {
            this.isValid = this.internals.validity.valid;
            this.onValidateInputEvent.emit(this.internals);
        }
    }
    /**
     * This is called on component before load
     */
    componentWillLoad() {
        this.computeChildCropper();
    }
    /**
     * This is called on component did load
     */
    componentDidLoad() {
        //
    }
    /**
     * Update the child cropper and render the result
     */
    computeChildCropper() {
        const croppers = Array.from(this.el.children)
            .filter(tab => tab.nodeName.toLowerCase() === 'x-cropper')
            .map(el => el);
        if (croppers.length > 0) {
            this.cropper = croppers[0];
            this.cropper.addEventListener('cropped', (e) => {
                e.detail.toBlob(blob => {
                    const temp = this.input.files[0];
                    const file = new File([blob], temp.name, { type: temp.type, lastModified: new Date().getTime() });
                    this.value = file;
                    this.onFileInputEvent.emit(file);
                    this.input.value = '';
                });
            });
            this.cropper.addEventListener('close', () => {
                console.log('Close cropper');
                this.input.value = '';
                this.formResetCallback();
            });
        }
    }
    /**
     * This called on input field is changed
     */
    onChangeInput() {
        var _a, _b, _c;
        if (this.cropper) {
            this.cropper.load(Object.assign(Object.assign({}, this.cropperOpcions), { source: (_a = this.input) === null || _a === void 0 ? void 0 : _a.files[0] }));
        }
        else {
            this.value = (_b = this.input) === null || _b === void 0 ? void 0 : _b.files[0];
            this.onFileInputEvent.emit((_c = this.input) === null || _c === void 0 ? void 0 : _c.files[0]);
        }
    }
    /**
     * This called on file is dragged to upload zone
     */
    onDragEnter() {
        this.isDragging = true;
        console.log('drag-enter');
    }
    /**
     * This called on file is leave the upload zone
     */
    onDragLeave() {
        setTimeout(() => this.isDragging = false, 100);
    }
    /**
     * Render component
     */
    render() {
        var _a;
        return (h(Host, { key: '91c1662315a735ecd388524555a14e8d9864b9ec', "data-for": this.name, class: cls({
                "loading": this.loading || this.isLoading,
                "disabled": this.isDisabled,
                "invalid": !this.isValid,
                "required": this.required,
            }) }, this.value && !this.withoutPreview && h("div", { key: '410e14ef0b9894aeac5f608885ba4cf84c243f8e', class: "preview" }, h("img", { key: 'ae117d78e0deb21797b82bee8ec8501114a5eda0', src: URL.createObjectURL(this.value), alt: this.capture, style: { maxWidth: this.maxWidth, maxHeight: this.maxHeight } })), h("div", { key: '6bd81f52776dcb2a722f34c5c740648c1c1205d7', class: cls({ "upload-zone": true, "on-active": this.value && !this.withoutPreview, "on-drag": this.isDragging }), draggable: true, onDragEnter: () => this.onDragEnter(), onDragLeave: () => this.onDragLeave(), onDragEnd: () => this.onDragLeave() }, h("x-icon", { key: '81b1b72bae8efab4a576dd0ab9ecef56a9de84a2', name: "upload", size: "2.5rem" }), h("p", { key: '82ab418f9f3a44cbdd9e4fe8c7a5553499ddcc0b', innerHTML: tinyMDtoHTML((_a = this.placeholder) !== null && _a !== void 0 ? _a : Lang.get('fields.cropper.upload')) }), h("input", { key: '0d96b7ca08d20b93c707371f69204714e3dfb647', ref: el => this.input = el, id: this.inputId, type: "file", required: this.required, disabled: this.isDisabled || this.loading || this.isLoading, placeholder: this.placeholder, accept: this.accept, capture: this.capture, onChange: () => this.onChangeInput() }), h("slot", { key: '40a1b9450e8bf04225a2bced94bc2bfa591d4059' }))));
    }
    static get is() { return "x-input-image"; }
    static get formAssociated() { return true; }
    static get originalStyleUrls() {
        return {
            "$": ["./style.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["style.css"]
        };
    }
    static get properties() {
        return {
            "name": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Element input name for forms keys"
                },
                "attribute": "name",
                "reflect": false
            },
            "placeholder": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Element input placeholder text"
                },
                "attribute": "placeholder",
                "reflect": false
            },
            "accept": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Element expected file type in file upload controls"
                },
                "attribute": "accept",
                "reflect": false,
                "defaultValue": "'image/*'"
            },
            "capture": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Element media capture input method in file upload controls"
                },
                "attribute": "capture",
                "reflect": false
            },
            "info": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Element input information block"
                },
                "attribute": "info",
                "reflect": false
            },
            "maxsize": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Element input maximun file size"
                },
                "attribute": "maxsize",
                "reflect": false
            },
            "maxWidth": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Element image maximun width size"
                },
                "attribute": "max-width",
                "reflect": false
            },
            "maxHeight": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Element image maximun height size"
                },
                "attribute": "max-height",
                "reflect": false
            },
            "required": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Element input required for forms validations"
                },
                "attribute": "required",
                "reflect": false
            },
            "loading": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Element show loading and block for edit"
                },
                "attribute": "loading",
                "reflect": false
            },
            "withoutPreview": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Element prevent show preview on change"
                },
                "attribute": "without-preview",
                "reflect": false
            },
            "disabled": {
                "type": "boolean",
                "mutable": true,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Element disabled state"
                },
                "attribute": "disabled",
                "reflect": false
            },
            "value": {
                "type": "unknown",
                "mutable": true,
                "complexType": {
                    "original": "File | null",
                    "resolved": "File",
                    "references": {
                        "File": {
                            "location": "global",
                            "id": "global::File"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Element input value"
                },
                "defaultValue": "null"
            }
        };
    }
    static get states() {
        return {
            "isValid": {},
            "isLoading": {},
            "isDisabled": {},
            "isDragging": {},
            "cropper": {}
        };
    }
    static get events() {
        return [{
                "method": "onValidateInputEvent",
                "name": "validated",
                "bubbles": false,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "On validate input event"
                },
                "complexType": {
                    "original": "ElementInternals",
                    "resolved": "ElementInternals",
                    "references": {
                        "ElementInternals": {
                            "location": "global",
                            "id": "global::ElementInternals"
                        }
                    }
                }
            }, {
                "method": "onFileInputEvent",
                "name": "file",
                "bubbles": false,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "On input load file"
                },
                "complexType": {
                    "original": "File",
                    "resolved": "File",
                    "references": {
                        "File": {
                            "location": "global",
                            "id": "global::File"
                        }
                    }
                }
            }];
    }
    static get methods() {
        return {
            "setCropperOptions": {
                "complexType": {
                    "signature": "(options: CropperOptions) => Promise<void>",
                    "parameters": [{
                            "name": "options",
                            "type": "{ source: string | File; sizes?: CropperSizeOption[]; }",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        },
                        "CropperOptions": {
                            "location": "import",
                            "path": "../x-cropper/component",
                            "id": "src/components/x-cropper/component.tsx::CropperOptions"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "Define cropper options",
                    "tags": []
                }
            }
        };
    }
    static get elementRef() { return "el"; }
    static get watchers() {
        return [{
                "propName": "value",
                "methodName": "watchValue"
            }];
    }
    static get listeners() {
        return [{
                "name": "slotchange",
                "method": "handleSlotChange",
                "target": undefined,
                "capture": false,
                "passive": false
            }];
    }
    static get attachInternalsMemberName() { return "internals"; }
}
