import { h, Host } from "@stencil/core";
import { createTemplateDocument, deleteTemplateDocument, getTemplate, VerdocsEndpoint } from "@verdocs/js-sdk";
import { DocIcon, FileIcon, JpgIcon, PageCountIcon, PdfIcon, PngIcon, TrashIcon } from "../../../utils/Icons";
import { SDKError } from "../../../utils/errors";
import { Store } from "../../../utils/Datastore";
/**
 * Displays an edit form that allows the user to view, add, or remove a template's attachments.
 * Note that an active session and valid template ID must be supplied.
 */
export class VerdocsTemplateAttachments {
    constructor() {
        this.templateListenerId = null;
        /**
         * The endpoint to use to communicate with Verdocs. If not set, the default endpoint will be used.
         */
        this.endpoint = VerdocsEndpoint.getDefault();
        /**
         * The template ID to edit.
         */
        this.templateId = '';
        this.uploading = false;
        this.progressLabel = 'Uploading...';
        this.progressPercent = 0;
        this.showDeleteError = false;
        this.confirmDeleteDocument = null;
        this.loading = true;
        this.template = null;
    }
    async componentWillLoad() {
        var _a, _b, _c;
        try {
            this.endpoint.loadSession();
            if (!this.templateId) {
                console.log(`[ROLES] Missing required template ID ${this.templateId}`);
                return;
            }
            if (!this.endpoint.session) {
                console.log('[ROLES] Unable to start builder session, must be authenticated');
                return;
            }
            this.listenToTemplate();
        }
        catch (e) {
            console.log('[TEMPLATE ATTACHMENTS] Error loading template', e);
            (_a = this.sdkError) === null || _a === void 0 ? void 0 : _a.emit(new SDKError(e.message, (_b = e.response) === null || _b === void 0 ? void 0 : _b.status, (_c = e.response) === null || _c === void 0 ? void 0 : _c.data));
        }
    }
    disconnectedCallback() {
        this.unlistenToTemplate();
    }
    async listenToTemplate() {
        this.unlistenToTemplate();
        Store.subscribe('templates', this.templateId, () => getTemplate(this.endpoint, this.templateId), false, (template) => {
            this.template = template;
            this.loading = false;
        });
    }
    unlistenToTemplate() {
        if (this.templateListenerId) {
            Store.store.delListener(this.templateListenerId);
            this.templateListenerId = null;
        }
    }
    handleCancel(e) {
        e.stopPropagation();
        this.exit.emit();
    }
    handleUploadProgress(percent) {
        if (percent >= 99) {
            this.progressPercent = 100;
            this.progressLabel = 'Processing...';
        }
        else {
            this.progressPercent = percent;
        }
    }
    async handleUpload(e) {
        var _a, _b, _c, _d;
        e.stopPropagation();
        const file = e.detail.file;
        if (!file) {
            return;
        }
        console.log('[ATTACHMENTS] Uploading...', file);
        this.uploading = true;
        this.progressLabel = 'Uploading...';
        try {
            const template = await createTemplateDocument(this.endpoint, this.templateId, file, this.handleUploadProgress.bind(this));
            console.log('[ATTACHMENTS] Created attachment', template);
            // TODO: Just updated it in place.
            this.template = await Store.getTemplate(this.endpoint, this.templateId, true);
            console.log('[ATTACHMENTS] Updated template', this.template);
            (_a = this.templateUpdated) === null || _a === void 0 ? void 0 : _a.emit({ endpoint: this.endpoint, template: this.template, event: 'attachments' });
            this.uploading = false;
            this.progressLabel = '';
            this.progressPercent = 0;
        }
        catch (e) {
            console.log('[ATTACHMENTS] Error creating template', e);
            (_b = this.sdkError) === null || _b === void 0 ? void 0 : _b.emit(new SDKError(e.message, (_c = e.response) === null || _c === void 0 ? void 0 : _c.status, (_d = e.response) === null || _d === void 0 ? void 0 : _d.data));
            this.uploading = false;
        }
    }
    handleNext(e) {
        var _a;
        e.stopPropagation();
        this.uploading = false;
        this.progressLabel = '';
        this.progressPercent = 0;
        (_a = this.next) === null || _a === void 0 ? void 0 : _a.emit({ template: this.template });
    }
    async confirmDelete() {
        await deleteTemplateDocument(this.endpoint, this.templateId, this.confirmDeleteDocument.id);
        // TODO: Update it in place
        this.template = await Store.getTemplate(this.endpoint, this.templateId, true);
        console.log('[ATTACHMENTS] New template', this.template);
        this.confirmDeleteDocument = null;
    }
    async handleDelete(document) {
        var _a;
        if ((((_a = this.template) === null || _a === void 0 ? void 0 : _a.documents) || []).length > 1) {
            this.confirmDeleteDocument = document;
        }
        else {
            this.showDeleteError = true;
        }
    }
    getFileIcon(document) {
        switch (document.mime) {
            case 'application/pdf':
                return PdfIcon;
            case 'image/jpeg':
                return JpgIcon;
            case 'image/png':
                return PngIcon;
            case 'application/msword':
            case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
                return DocIcon;
        }
        return FileIcon;
    }
    render() {
        var _a, _b;
        if (!this.endpoint.session) {
            return (h(Host, null, h("verdocs-component-error", { message: "You must be authenticated to use this module." })));
        }
        if (this.loading) {
            return (h(Host, { class: "loading" }, h("verdocs-loader", null)));
        }
        // This is meant to be a companion for larger visual experiences so we just go blank on errors for now.
        if (!this.endpoint.session || !this.template) {
            return h(Host, { class: "empty" });
        }
        return (h(Host, null, h("h5", null, "Existing Attachments"), h("div", { class: "attachments" }, (((_a = this.template) === null || _a === void 0 ? void 0 : _a.documents) || []).map(document => (h("div", { class: "attachment" }, h("div", { class: "file-icon", innerHTML: this.getFileIcon(document) }), h("div", { class: "filename", title: document.name }, document.name), h("div", { class: "pages" }, h("div", { class: "count" }, document.pages), h("div", { class: "pages-icon", innerHTML: PageCountIcon })), h("div", { class: "trash-icon", innerHTML: TrashIcon, onClick: () => this.handleDelete(document) }))))), h("h5", null, "Attach a New Document"), this.uploading ? (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("verdocs-file-chooser", { onFileSelected: e => this.handleUpload(e) })), h("div", { class: "buttons" }, h("verdocs-button", { variant: "outline", label: "Cancel", size: "small", onClick: e => this.handleCancel(e), disabled: this.uploading }), h("verdocs-button", { label: "Next", size: "small", onClick: e => this.handleNext(e), disabled: !(((_b = this.template) === null || _b === void 0 ? void 0 : _b.documents) || []).length || this.uploading })), this.showDeleteError && (h("verdocs-ok-dialog", { heading: "Unable to Delete Attachment", message: "Templates must contain at least one attachment.", onNext: () => (this.showDeleteError = false) })), this.confirmDeleteDocument && (h("verdocs-ok-dialog", { heading: "Delete this Attachment?", message: "This operation cannot be undone. All fields placed<br />on the deleted attachment will also be removed.", onNext: () => this.confirmDelete(), showCancel: true, onExit: () => {
                this.confirmDeleteDocument = null;
            } }))));
    }
    static get is() { return "verdocs-template-attachments"; }
    static get originalStyleUrls() {
        return {
            "$": ["verdocs-template-attachments.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["verdocs-template-attachments.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()"
            },
            "templateId": {
                "type": "string",
                "attribute": "template-id",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The template ID to edit."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "''"
            }
        };
    }
    static get states() {
        return {
            "uploading": {},
            "progressLabel": {},
            "progressPercent": {},
            "showDeleteError": {},
            "confirmDeleteDocument": {},
            "loading": {},
            "template": {}
        };
    }
    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 clicks the next button."
                },
                "complexType": {
                    "original": "{template: ITemplate}",
                    "resolved": "{ template: ITemplate; }",
                    "references": {
                        "ITemplate": {
                            "location": "import",
                            "path": "@verdocs/js-sdk",
                            "id": "node_modules::ITemplate"
                        }
                    }
                }
            }, {
                "method": "templateUpdated",
                "name": "templateUpdated",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Event fired when the user updates the template."
                },
                "complexType": {
                    "original": "{endpoint: VerdocsEndpoint; template: ITemplate; event: string}",
                    "resolved": "{ endpoint: VerdocsEndpoint; template: ITemplate; event: string; }",
                    "references": {
                        "VerdocsEndpoint": {
                            "location": "import",
                            "path": "@verdocs/js-sdk",
                            "id": "node_modules::VerdocsEndpoint"
                        },
                        "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"
                        }
                    }
                }
            }];
    }
}
//# sourceMappingURL=verdocs-template-attachments.js.map
