var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try {
            step(generator.next(value));
        }
        catch (e) {
            reject(e);
        } }
        function rejected(value) { try {
            step(generator["throw"](value));
        }
        catch (e) {
            reject(e);
        } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { Host, h, Fragment } from "@stencil/core";
export class CpslFileUpload {
    constructor() {
        this.inputId = `cpsl-file-upload-${inputIds++}`;
        this.handleDrop = (ev) => __awaiter(this, void 0, void 0, function* () {
            var _a;
            ev.preventDefault();
            const item = (_a = Array.from(ev.dataTransfer.items)) === null || _a === void 0 ? void 0 : _a[0];
            if (item && this.isValidFile(item.type)) {
                const file = item.getAsFile();
                yield this.addFile(file);
            }
            this.dragOver = false;
            this.dragError = false;
            this.cpslOnDrop.emit(ev);
        });
        this.handleDragEnter = (ev) => {
            var _a;
            ev.preventDefault();
            this.dragOver = true;
            const item = (_a = Array.from(ev.dataTransfer.items)) === null || _a === void 0 ? void 0 : _a[0];
            if (item && this.isValidFile(item.type)) {
                this.dragError = true;
            }
            this.cpslOnDragEnter.emit(ev);
        };
        this.handleDragLeave = (ev) => {
            ev.preventDefault();
            this.dragOver = false;
            this.dragError = false;
            this.cpslOnDragLeave.emit(ev);
        };
        this.handleInputChange = (ev) => __awaiter(this, void 0, void 0, function* () {
            ev.preventDefault();
            const input = this.inputEl;
            if (input.files.length) {
                const file = input.files[0];
                if (this.isValidFile(file.type)) {
                    yield this.addFile(file);
                }
            }
        });
        this.isValidFile = (type) => {
            var _a;
            if (((_a = this.fileTypes) === null || _a === void 0 ? void 0 : _a.length) ? !this.fileTypes.includes(type) : false) {
                return false;
            }
            return true;
        };
        this.addFile = (file) => __awaiter(this, void 0, void 0, function* () {
            this.file = file;
            this.cpslFileChange.emit(file);
            this.uploadError = false;
            this.isUploading = true;
            const uploadSuccess = this.uploadFile ? yield this.uploadFile(file) : true;
            if (!uploadSuccess) {
                this.uploadError = true;
                const input = this.inputEl;
                input.value = '';
            }
            this.isUploading = false;
        });
        this.removeFile = (e) => {
            e.preventDefault();
            this.file = undefined;
            const input = this.inputEl;
            input.value = '';
            this.cpslFileRemoved.emit();
        };
        this.file = undefined;
        this.dragOver = undefined;
        this.dragError = undefined;
        this.isUploading = undefined;
        this.uploadError = undefined;
        this.disabled = false;
        this.errorText = undefined;
        this.externalFilename = undefined;
        this.externalSrc = undefined;
        this.fileTypes = undefined;
        this.helperText = undefined;
        this.label = undefined;
        this.required = false;
        this.showOptionalLabel = false;
        this.uploadFile = undefined;
    }
    get inputEl() {
        return this.el.shadowRoot.getElementById(this.inputId);
    }
    get FileContent() {
        var _a;
        const hasFile = Boolean(this.file) || Boolean(this.externalSrc);
        const isUploading = this.isUploading;
        const error = this.uploadError;
        const text = !hasFile ? (h(Fragment, null, 'Drag file here or ', h("cpsl-text", { class: "inline-text", variant: "bodyXS" }, "upload file"))) : isUploading ? (`${this.file.name} is uploading`) : error ? ('Upload Failed') : (((_a = this.file) === null || _a === void 0 ? void 0 : _a.name) || this.externalFilename || '');
        const TopElement = !hasFile ? (h("cpsl-icon", { icon: "image" })) : isUploading ? (h("cpsl-spinner", null)) : error ? (h("cpsl-icon", { icon: "close" })) : (h("img", { class: "sample-img", src: this.file ? URL.createObjectURL(this.file) : this.externalSrc, alt: "Sample Image" }));
        return (h(Fragment, null, TopElement, h("span", { class: "sample-image-name-container" }, h("cpsl-text", { class: "sample-image-name", variant: "bodyXS" }, text), hasFile && !error && !isUploading && h("cpsl-icon", { icon: "close", onClick: this.removeFile }))));
    }
    render() {
        var _a, _b, _c;
        return (h(Host, { key: '16d9e9ac3a79cbaab554cd9b8901f2b5a930327d' }, this.label && (h("label", { key: 'a0d3cba9de77959cc1fa9d415e943800997fa1db', class: "label", htmlFor: this.inputId }, this.label, this.required ? '*' : ' ', !this.required && this.showOptionalLabel ? h("span", { class: "optional-label" }, "(optional)") : '')), h("slot", { key: '2ae7b7de344204f341ce8aa8044908bdc183cee1', name: "label" }), h("div", { key: 'd4ba3206869ed403217e37b20e9557784f98cfd2', class: { 'container': true, 'error': Boolean(this.errorText), 'drag': this.dragOver, 'drag-error': this.dragError } }, h("div", { key: '7f344b81e11e07b00e8cdbee5a89cc4300e02b4b', class: { 'label-container': true } }, h("slot", { key: 'c187ed9574eab9e21669a04d6a9d663adabcab75', name: "left-content" })), h("div", { key: '6bc08c41c298577cf71ca7f7209764d62fc42641', class: { 'file-container': true } }, this.FileContent), h("input", { key: '1696d38e71235671341b9e4388fa2a8478d5b259', id: this.inputId, type: "file", accept: (_b = (_a = this.fileTypes) === null || _a === void 0 ? void 0 : _a.join(', ')) !== null && _b !== void 0 ? _b : '*', files: this.file ? [this.file] : undefined, onDrop: this.handleDrop, onDragEnter: this.handleDragEnter, onDragLeave: this.handleDragLeave, onChange: this.handleInputChange, disabled: this.disabled })), (this.errorText || this.helperText) && (h("div", { key: 'f2c25a388395daf16082856e8135d952e4166247', class: { 'helper-text-container': true, 'error-text': Boolean(this.errorText) } }, h("span", { key: 'd6af4e67851048e79f3342156e35b87928dbef7c' }, (_c = this.errorText) !== null && _c !== void 0 ? _c : this.helperText)))));
    }
    static get is() { return "cpsl-file-upload"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["cpsl-file-upload.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["cpsl-file-upload.css"]
        };
    }
    static get properties() {
        return {
            "disabled": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "If the input is disabled.\nDefault is: false."
                },
                "attribute": "disabled",
                "reflect": true,
                "defaultValue": "false"
            },
            "errorText": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Error text to show below the input. If this is provided the input will enter an error state."
                },
                "attribute": "error-text",
                "reflect": false
            },
            "externalFilename": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Filename for the external source of the selected file."
                },
                "attribute": "external-filename",
                "reflect": false
            },
            "externalSrc": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "External source for the selected file."
                },
                "attribute": "external-src",
                "reflect": false
            },
            "fileTypes": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "string[]",
                    "resolved": "string[]",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Valid file types."
                }
            },
            "helperText": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Helper text to show below the input. If `\"errorText\"` is provided that will take precedence."
                },
                "attribute": "helper-text",
                "reflect": false
            },
            "label": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "The label for the input."
                },
                "attribute": "label",
                "reflect": 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"
            },
            "showOptionalLabel": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "If `true`, the label will display an \"optional\" tag."
                },
                "attribute": "show-optional-label",
                "reflect": false,
                "defaultValue": "false"
            },
            "uploadFile": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "(file: File) => Promise<boolean>",
                    "resolved": "(file: File) => Promise<boolean>",
                    "references": {
                        "File": {
                            "location": "global",
                            "id": "global::File"
                        },
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Function to trigger file upload to server.\nReturns: boolean indicating success or failure."
                }
            }
        };
    }
    static get states() {
        return {
            "file": {},
            "dragOver": {},
            "dragError": {},
            "isUploading": {},
            "uploadError": {}
        };
    }
    static get events() {
        return [{
                "method": "cpslOnDrop",
                "name": "cpslOnDrop",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Emitted when the file is dropped in the input."
                },
                "complexType": {
                    "original": "DragEvent",
                    "resolved": "DragEvent",
                    "references": {
                        "DragEvent": {
                            "location": "global",
                            "id": "global::DragEvent"
                        }
                    }
                }
            }, {
                "method": "cpslOnDragEnter",
                "name": "cpslOnDragEnter",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Emitted when the file drag enters the input."
                },
                "complexType": {
                    "original": "DragEvent",
                    "resolved": "DragEvent",
                    "references": {
                        "DragEvent": {
                            "location": "global",
                            "id": "global::DragEvent"
                        }
                    }
                }
            }, {
                "method": "cpslOnDragLeave",
                "name": "cpslOnDragLeave",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Emitted when the file drag leaves the input."
                },
                "complexType": {
                    "original": "DragEvent",
                    "resolved": "DragEvent",
                    "references": {
                        "DragEvent": {
                            "location": "global",
                            "id": "global::DragEvent"
                        }
                    }
                }
            }, {
                "method": "cpslFileChange",
                "name": "cpslFileChange",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Emitted when the file changes."
                },
                "complexType": {
                    "original": "File",
                    "resolved": "File",
                    "references": {
                        "File": {
                            "location": "global",
                            "id": "global::File"
                        }
                    }
                }
            }, {
                "method": "cpslFileRemoved",
                "name": "cpslFileRemoved",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Emitted when the file is removed."
                },
                "complexType": {
                    "original": "void",
                    "resolved": "void",
                    "references": {}
                }
            }];
    }
    static get elementRef() { return "el"; }
}
let inputIds = 0;
//# sourceMappingURL=cpsl-file-upload.js.map
