import { createTemplate, VerdocsEndpoint } from "@verdocs/js-sdk";
import { h, Host } from "@stencil/core";
import { SDKError } from "../../../utils/errors";
const FileIcon = '<svg focusable="false" aria-hidden="true" viewBox="0 0 24 24"><path d="M6 2c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6H6zm7 7V3.5L18.5 9H13z"></path></svg>';
/**
 * Displays a file upload mechanism suitable for the first step of creating a template.
 * This is typically the first step in a template creation workflow.
 */
export class VerdocsTemplateCreate {
    constructor() {
        /**
         * The endpoint to use to communicate with Verdocs. If not set, the default endpoint will be used.
         */
        this.endpoint = VerdocsEndpoint.getDefault();
        this.maxSize = 20.5 * 1024 * 1024;
        this.creating = false;
        this.progressLabel = 'Uploading...';
        this.progressPercent = 0;
        this.errorMessage = '';
    }
    componentWillLoad() {
        this.endpoint.setTimeout(30000);
        this.endpoint.loadSession();
    }
    handleFileChanged(e) {
        var _a;
        this.errorMessage = '';
        this.file = ((_a = e.target.files) === null || _a === void 0 ? void 0 : _a[0]) || null;
        console.log('[CREATE] Selected file', this.file);
        const totalSize = this.file.size;
        if (totalSize > this.maxSize) {
            this.errorMessage = 'Total file size must not exceed 20MB.';
        }
    }
    handleUpload(e) {
        e.stopPropagation();
        const fileElem = document.getElementById('verdocs-template-create-file');
        fileElem.click();
    }
    handleCancel(e) {
        e.stopPropagation();
        this.exit.emit();
    }
    async handleSubmit(e) {
        var _a, _b, _c, _d, _e;
        e.stopPropagation();
        // Should be true if we're here because onClick is only enabled then. We're just guarding this for Typescript.
        if (!this.file) {
            return;
        }
        this.creating = true;
        this.progressLabel = 'Uploading...';
        try {
            const template = await createTemplate(this.endpoint, {
                name: this.file.name,
                // TODO: Make optional in the SDK
                initial_reminder: 0,
                followup_reminders: 0,
                documents: [this.file],
            }, percent => {
                if (percent >= 99) {
                    this.progressLabel = 'Processing...';
                    this.progressPercent = 100;
                }
                else {
                    this.progressPercent = percent;
                }
            });
            console.log('[CREATE] Created template', template);
            (_a = this.templateCreated) === null || _a === void 0 ? void 0 : _a.emit({ endpoint: this.endpoint, template, templateId: template.id });
            (_b = this.next) === null || _b === void 0 ? void 0 : _b.emit(template);
            this.creating = false;
            this.progressLabel = '';
            this.progressPercent = 0;
        }
        catch (e) {
            console.log('[CREATE] Error creating template', e);
            (_c = this.sdkError) === null || _c === void 0 ? void 0 : _c.emit(new SDKError(e.message, (_d = e.response) === null || _d === void 0 ? void 0 : _d.status, (_e = e.response) === null || _e === void 0 ? void 0 : _e.data));
            this.creating = false;
        }
    }
    render() {
        if (!this.endpoint.session) {
            return (h(Host, null, h("verdocs-component-error", { message: "You must be authenticated to use this module." })));
        }
        return (h(Host, null, h("form", { onSubmit: e => e.preventDefault(), onClick: e => e.stopPropagation(), autocomplete: "off" }, h("input", { type: "file", id: "verdocs-template-create-file", multiple: true, accept: ".pdf,application/pdf,.doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document", style: { display: 'none' }, onChange: e => this.handleFileChanged(e) }), this.creating ? (h("div", { class: "loader-wrapper" }, h("verdocs-loader", null), this.progressLabel && (h("div", { class: "progress-wrapper" }, h("verdocs-progress-bar", { showPercent: true, percent: this.progressPercent, label: this.progressLabel }))))) : (h("div", { class: "upload-box", onDrop: (e) => {
                e.preventDefault();
                e.target.classList.remove('drag-over');
                this.file = e.dataTransfer.files[0];
                if (this.file.size > this.maxSize) {
                    this.errorMessage = 'Total file size must not exceed 20MB.';
                }
            }, onDragOver: (e) => {
                e.preventDefault();
                e.dataTransfer.dropEffect = 'copy';
            }, onDragEnter: (e) => e.target.classList.add('drag-over'), onDragLeave: (e) => e.target.classList.remove('drag-over') }, h("span", { innerHTML: FileIcon, style: { display: 'flex', justifyContent: 'center' } }), h("p", null, this.file ? this.file.name : 'Drag and drop your files here'), h("p", { class: "subscript" }, "Supported files: PDF, Word"), h("verdocs-button", { label: this.file ? 'Select a different file' : 'Select a file from your computer', size: "small", onClick: e => this.handleUpload(e) }))), !!this.errorMessage && h("div", { class: "error" }, this.errorMessage), h("div", { class: "buttons" }, h("verdocs-button", { variant: "outline", label: "Cancel", size: "small", onClick: e => this.handleCancel(e), disabled: this.creating }), h("verdocs-button", { label: "Next", size: "small", onClick: e => this.handleSubmit(e), disabled: !this.file || this.creating || !!this.errorMessage })))));
    }
    static get is() { return "verdocs-template-create"; }
    static get originalStyleUrls() {
        return {
            "$": ["verdocs-template-create.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["verdocs-template-create.css"]
        };
    }
    static get properties() {
        return {
            "endpoint": {
                "type": "unknown",
                "attribute": "endpoint",
                "mutable": false,
                "complexType": {
                    "original": "VerdocsEndpoint",
                    "resolved": "VerdocsEndpoint",
                    "references": {
                        "VerdocsEndpoint": {
                            "location": "import",
                            "path": "@verdocs/js-sdk",
                            "id": "node_modules::VerdocsEndpoint"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The endpoint to use to communicate with Verdocs. If not set, the default endpoint will be used."
                },
                "getter": false,
                "setter": false,
                "defaultValue": "VerdocsEndpoint.getDefault()"
            },
            "maxSize": {
                "type": "number",
                "attribute": "max-size",
                "mutable": true,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "20.5 * 1024 * 1024"
            }
        };
    }
    static get states() {
        return {
            "file": {},
            "creating": {},
            "progressLabel": {},
            "progressPercent": {},
            "errorMessage": {}
        };
    }
    static get events() {
        return [{
                "method": "exit",
                "name": "exit",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Event fired when the step is cancelled. This is called exit to avoid conflicts with the JS-reserved \"cancel\" event name."
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }, {
                "method": "next",
                "name": "next",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Event fired when the user changes the type."
                },
                "complexType": {
                    "original": "ITemplate",
                    "resolved": "ITemplate",
                    "references": {
                        "ITemplate": {
                            "location": "import",
                            "path": "@verdocs/js-sdk",
                            "id": "node_modules::ITemplate"
                        }
                    }
                }
            }, {
                "method": "sdkError",
                "name": "sdkError",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Event fired if an error occurs. The event details will contain information about the error. Most errors will\nterminate the process, and the calling application should correct the condition and re-render the component."
                },
                "complexType": {
                    "original": "SDKError",
                    "resolved": "SDKError",
                    "references": {
                        "SDKError": {
                            "location": "import",
                            "path": "../../../utils/errors",
                            "id": "src/utils/errors.ts::SDKError"
                        }
                    }
                }
            }, {
                "method": "templateCreated",
                "name": "templateCreated",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Event fired when the user updates the template."
                },
                "complexType": {
                    "original": "{endpoint: VerdocsEndpoint; template: ITemplate; templateId: string}",
                    "resolved": "{ endpoint: VerdocsEndpoint; template: ITemplate; templateId: string; }",
                    "references": {
                        "VerdocsEndpoint": {
                            "location": "import",
                            "path": "@verdocs/js-sdk",
                            "id": "node_modules::VerdocsEndpoint"
                        },
                        "ITemplate": {
                            "location": "import",
                            "path": "@verdocs/js-sdk",
                            "id": "node_modules::ITemplate"
                        }
                    }
                }
            }];
    }
}
//# sourceMappingURL=verdocs-template-create.js.map
