import { p as proxyCustomElement, H, c as createEvent, h, d as Host } from './p-D16h8pzh.js';
import { VerdocsEndpoint, getTemplate, createTemplateDocument, deleteTemplateDocument } from '@verdocs/js-sdk';
import { D as DocIcon, P as PngIcon, J as JpgIcon, a as PdfIcon, F as FileIcon, b as PageCountIcon, T as TrashIcon } from './p-7LXbcjVz.js';
import { S as SDKError } from './p-C1sRVZWv.js';
import { S as Store } from './p-DmsV595e.js';
import { d as defineCustomElement$7 } from './p-BNrp2UP2.js';
import { d as defineCustomElement$6 } from './p-DsCKNQPC.js';
import { d as defineCustomElement$5 } from './p-CZTe2XIO.js';
import { d as defineCustomElement$4 } from './p-DDTha7DK.js';
import { d as defineCustomElement$3 } from './p-Bv-L0hsU.js';
import { d as defineCustomElement$2 } from './p-CQ-UXlBO.js';
import { d as defineCustomElement$1 } from './p-C2M87N-a.js';

const verdocsTemplateAttachmentsCss = "@-webkit-keyframes verdocs-field-pulse{0%{background-color:rgba(0, 0, 0, 0.35)}50%{background-color:rgba(0, 0, 0, 0)}100%{background-color:rgba(0, 0, 0, 0.35)}}@keyframes verdocs-field-pulse{0%{background-color:rgba(0, 0, 0, 0.35)}50%{background-color:rgba(0, 0, 0, 0)}100%{background-color:rgba(0, 0, 0, 0.35)}}verdocs-template-attachments{font-family:\"Inter\", -apple-system, \"Segoe UI\", \"Roboto\", \"Helvetica Neue\", sans-serif}verdocs-template-attachments h5{font-size:16px;font-weight:bold;margin:0 0 10px 0;color:#46497d}verdocs-template-attachments .attachments{margin:0 0 40px 0}verdocs-template-attachments .attachment{display:-ms-flexbox;display:flex;padding:5px 0;-webkit-column-gap:15px;-moz-column-gap:15px;column-gap:15px;-ms-flex-align:center;align-items:center;-ms-flex-direction:row;flex-direction:row;color:#33364b}verdocs-template-attachments .attachment:hover .trash-icon{display:-ms-flexbox;display:flex}verdocs-template-attachments .attachment:hover .pages{display:none}verdocs-template-attachments svg{width:28px;height:28px;fill:#5c6575;margin:2px 0 0 0}verdocs-template-attachments .file-icon{-ms-flex:0;flex:0}verdocs-template-attachments .pages{width:24px;height:24px;-ms-flex:0 0 24px;flex:0 0 24px;padding-left:4px;position:relative;margin:-10px 0 0 0}verdocs-template-attachments .pages .pages-icon{top:0;left:0;width:24px;height:24px;position:absolute}verdocs-template-attachments .pages .count{top:11px;left:7px;z-index:1;width:18px;font-size:12px;font-weight:500;position:absolute;text-align:center;letter-spacing:-2px}verdocs-template-attachments .filename{-ms-flex:1;flex:1;display:block;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;border-bottom:1px dotted #cccccc}verdocs-template-attachments .trash-icon{-ms-flex:0;flex:0;display:none}verdocs-template-attachments .trash-icon:hover{cursor:pointer}verdocs-template-attachments verdocs-file-chooser{margin:10px 0;border:2px dashed #979797}verdocs-template-attachments .loader-wrapper{background-color:#ffffff;display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;-webkit-box-sizing:border-box;box-sizing:border-box;position:relative;width:320px;height:320px;text-align:center;border:2px dashed #979797;-ms-flex-pack:end;justify-content:flex-end}verdocs-template-attachments .progress-wrapper{padding:20px}verdocs-template-attachments .buttons{display:-ms-flexbox;display:flex;-webkit-column-gap:8px;-moz-column-gap:8px;column-gap:8px;margin-top:16px;-ms-flex-align:center;align-items:center;-ms-flex-direction:row;flex-direction:row;-ms-flex-pack:end;justify-content:flex-end}verdocs-template-attachments .buttons .flex-fill{-ms-flex:1;flex:1}verdocs-template-attachments ::-webkit-input-placeholder{color:#aaaaaa}verdocs-template-attachments ::-moz-placeholder{color:#aaaaaa}verdocs-template-attachments :-ms-input-placeholder{color:#aaaaaa}verdocs-template-attachments ::-ms-input-placeholder{color:#aaaaaa}verdocs-template-attachments ::placeholder{color:#aaaaaa}";

const VerdocsTemplateAttachments = /*@__PURE__*/ proxyCustomElement(class VerdocsTemplateAttachments extends H {
    constructor() {
        super();
        this.__registerHost();
        this.exit = createEvent(this, "exit");
        this.next = createEvent(this, "next");
        this.templateUpdated = createEvent(this, "templateUpdated");
        this.sdkError = createEvent(this, "sdkError");
        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 style() { return verdocsTemplateAttachmentsCss; }
}, [256, "verdocs-template-attachments", {
        "endpoint": [16],
        "templateId": [1, "template-id"],
        "uploading": [32],
        "progressLabel": [32],
        "progressPercent": [32],
        "showDeleteError": [32],
        "confirmDeleteDocument": [32],
        "loading": [32],
        "template": [32]
    }]);
function defineCustomElement() {
    if (typeof customElements === "undefined") {
        return;
    }
    const components = ["verdocs-template-attachments", "verdocs-button", "verdocs-component-error", "verdocs-dialog", "verdocs-file-chooser", "verdocs-loader", "verdocs-ok-dialog", "verdocs-progress-bar"];
    components.forEach(tagName => { switch (tagName) {
        case "verdocs-template-attachments":
            if (!customElements.get(tagName)) {
                customElements.define(tagName, VerdocsTemplateAttachments);
            }
            break;
        case "verdocs-button":
            if (!customElements.get(tagName)) {
                defineCustomElement$7();
            }
            break;
        case "verdocs-component-error":
            if (!customElements.get(tagName)) {
                defineCustomElement$6();
            }
            break;
        case "verdocs-dialog":
            if (!customElements.get(tagName)) {
                defineCustomElement$5();
            }
            break;
        case "verdocs-file-chooser":
            if (!customElements.get(tagName)) {
                defineCustomElement$4();
            }
            break;
        case "verdocs-loader":
            if (!customElements.get(tagName)) {
                defineCustomElement$3();
            }
            break;
        case "verdocs-ok-dialog":
            if (!customElements.get(tagName)) {
                defineCustomElement$2();
            }
            break;
        case "verdocs-progress-bar":
            if (!customElements.get(tagName)) {
                defineCustomElement$1();
            }
            break;
    } });
}

export { VerdocsTemplateAttachments as V, defineCustomElement as d };
//# sourceMappingURL=p-BR7qeKJV.js.map

//# sourceMappingURL=p-BR7qeKJV.js.map