import { getTemplate, VerdocsEndpoint } from "@verdocs/js-sdk";
import { h, Host } from "@stencil/core";
import { SDKError } from "../../../utils/errors";
import { Store } from "../../../utils/Datastore";
/**
 * Display a template building experience. Several event callbacks provide status updates to the
 * parent application to support interface updates.
 *
 * ```ts
 * <verdocs-build
 *   templateId={TEMPLATE_ID} step="preview"
 *   onSend={({detail}) => { console.log('Sent envelope from template', detail) }}
 *   onSdkError={({ detail }) => { console.log('SDK error', detail) }}
 *   />
 * ```
 */
export class VerdocsBuild {
    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 ID of the template to create the document from. Unlike most other components, this is an optional parameter here.
         * If the template ID is known, `step` may also be specified to force displaying a specific step in the creation process.
         * If it is not specified, `step` will be ignored and the create step will be shown.
         */
        this.templateId = null;
        /**
         * The step in the creation process to display.
         */
        this.step = 'preview';
        this.loading = true;
        this.template = null;
    }
    onTemplateIdChanged(newTemplateId, oldTemplateId) {
        if (!oldTemplateId && newTemplateId && this.step === 'attachments') {
            this.step = 'preview';
        }
        this.loadTemplate(newTemplateId).catch((e) => console.log('Unknown Error', e));
    }
    onStepChanged() {
        // We reload the template here even if only the step changed in case
        // we were out of sync before
        this.loadTemplate(this.templateId).catch((e) => console.log('Unknown Error', e));
    }
    async componentWillLoad() {
        var _a, _b, _c, _d, _e, _f;
        try {
            this.endpoint.loadSession();
            if (!this.endpoint.session) {
                console.log('[BUILD] Unable to start builder session, must be authenticated');
                return;
            }
            if (!this.templateId) {
                console.log(`[BUILD] No template ID, activating upload mode`);
                this.step = 'attachments';
                this.loading = false;
                return;
            }
            try {
                this.loadTemplate(this.templateId).catch(e => console.log('[BUILD] Unable to load template', e));
            }
            catch (e) {
                console.log('[BUILD] 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));
            }
        }
        catch (e) {
            console.log('[BUILD] Error with builder session', e);
            (_d = this.sdkError) === null || _d === void 0 ? void 0 : _d.emit(new SDKError(e.message, (_e = e.response) === null || _e === void 0 ? void 0 : _e.status, (_f = e.response) === null || _f === void 0 ? void 0 : _f.data));
        }
    }
    async loadTemplate(templateId) {
        if (templateId) {
            Store.subscribe('templates', this.templateId, () => getTemplate(this.endpoint, this.templateId), false, (template) => {
                this.template = template;
                this.loading = false;
            });
        }
    }
    disconnectedCallback() {
        console.log('[BUILD] Disconnected');
        this.unlistenToTemplate();
    }
    unlistenToTemplate() {
        if (this.templateListenerId) {
            Store.store.delListener(this.templateListenerId);
            this.templateListenerId = null;
        }
    }
    handleCancel() {
        var _a;
        this.step = 'preview';
        (_a = this.cancel) === null || _a === void 0 ? void 0 : _a.emit();
    }
    async handleTemplateCreated(templateId) {
        var _a;
        await this.loadTemplate(templateId);
        this.templateId = templateId;
        this.step = 'roles';
        (_a = this.stepChanged) === null || _a === void 0 ? void 0 : _a.emit('roles');
    }
    async handleRolesUpdated(e) {
        var _a;
        (_a = this.templateUpdated) === null || _a === void 0 ? void 0 : _a.emit(e.detail);
    }
    async handleTemplateUpdated(e) {
        var _a;
        (_a = this.templateUpdated) === null || _a === void 0 ? void 0 : _a.emit(e.detail);
    }
    handleAttachmentsNext() {
        var _a;
        this.step = 'roles';
        (_a = this.stepChanged) === null || _a === void 0 ? void 0 : _a.emit('roles');
    }
    handleRolesNext() {
        var _a;
        this.step = 'fields';
        (_a = this.stepChanged) === null || _a === void 0 ? void 0 : _a.emit('fields');
    }
    handleStepChanged(step) {
        var _a;
        this.step = step;
        (_a = this.stepChanged) === null || _a === void 0 ? void 0 : _a.emit(step);
    }
    render() {
        if (this.loading) {
            return (h(Host, { class: "loading" }, h("verdocs-loader", null)));
        }
        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("div", { class: "content" }, h("verdocs-template-build-tabs", { endpoint: this.endpoint, templateId: this.templateId, step: this.step, onSdkError: e => { var _a; return (_a = this.sdkError) === null || _a === void 0 ? void 0 : _a.emit(e.detail); }, onStepChanged: e => this.handleStepChanged(e.detail) }), this.step === 'attachments' && (h("verdocs-template-attachments", { templateId: this.templateId, endpoint: this.endpoint, onExit: () => this.handleCancel(), onNext: () => this.handleAttachmentsNext(), onTemplateUpdated: e => this.handleTemplateUpdated(e) })), this.step === 'roles' && (h("verdocs-template-roles", { templateId: this.templateId, endpoint: this.endpoint, onExit: () => this.handleCancel(), onNext: () => this.handleRolesNext(), onRolesUpdated: e => this.handleRolesUpdated(e) })), this.step === 'settings' && h("verdocs-template-settings", { templateId: this.templateId, endpoint: this.endpoint, onTemplateUpdated: e => this.handleTemplateUpdated(e) }), this.step === 'fields' && h("verdocs-template-fields", { templateId: this.templateId, endpoint: this.endpoint, onTemplateUpdated: e => this.handleTemplateUpdated(e) }), this.step === 'preview' && (h("div", { class: "preview-container" }, h("div", { class: "preview-send-wrapper" }, h("verdocs-send", { templateId: this.templateId, endpoint: this.endpoint, onSend: e => { var _a; return (_a = this.send) === null || _a === void 0 ? void 0 : _a.emit(e.detail); }, style: { width: '100%' } })), h("div", { class: "preview-preview-wrapper" }, h("verdocs-preview", { templateId: this.templateId, endpoint: this.endpoint, style: { display: 'flex', flex: '1', maxWidth: '1000px' } })))))));
    }
    static get is() { return "verdocs-build"; }
    static get originalStyleUrls() {
        return {
            "$": ["verdocs-build.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["verdocs-build.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": true,
                "complexType": {
                    "original": "string | null",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The ID of the template to create the document from. Unlike most other components, this is an optional parameter here.\nIf the template ID is known, `step` may also be specified to force displaying a specific step in the creation process.\nIf it is not specified, `step` will be ignored and the create step will be shown."
                },
                "getter": false,
                "setter": false,
                "reflect": true,
                "defaultValue": "null"
            },
            "step": {
                "type": "string",
                "attribute": "step",
                "mutable": true,
                "complexType": {
                    "original": "TVerdocsBuildStep",
                    "resolved": "\"attachments\" | \"fields\" | \"preview\" | \"roles\" | \"settings\"",
                    "references": {
                        "TVerdocsBuildStep": {
                            "location": "local",
                            "path": "/Users/chad/projects/verdocs/web-sdk/verdocs-web-sdk/src/components/embeds/verdocs-build/verdocs-build.tsx",
                            "id": "src/components/embeds/verdocs-build/verdocs-build.tsx::TVerdocsBuildStep"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The step in the creation process to display."
                },
                "getter": false,
                "setter": false,
                "reflect": true,
                "defaultValue": "'preview'"
            }
        };
    }
    static get states() {
        return {
            "loading": {},
            "template": {}
        };
    }
    static get events() {
        return [{
                "method": "cancel",
                "name": "cancel",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Event fired if the user clicks Cancel."
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }, {
                "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": "stepChanged",
                "name": "stepChanged",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Event fired when the user selects a different step."
                },
                "complexType": {
                    "original": "TVerdocsBuildStep",
                    "resolved": "\"attachments\" | \"fields\" | \"preview\" | \"roles\" | \"settings\"",
                    "references": {
                        "TVerdocsBuildStep": {
                            "location": "local",
                            "path": "/Users/chad/projects/verdocs/web-sdk/verdocs-web-sdk/src/components/embeds/verdocs-build/verdocs-build.tsx",
                            "id": "src/components/embeds/verdocs-build/verdocs-build.tsx::TVerdocsBuildStep"
                        }
                    }
                }
            }, {
                "method": "send",
                "name": "send",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "The user completed the Send form and clicked send."
                },
                "complexType": {
                    "original": "{recipients: ICreateEnvelopeRecipientFromTemplate[]; name: string; template_id: string}",
                    "resolved": "{ recipients: ICreateEnvelopeRecipientFromTemplate[]; name: string; template_id: string; }",
                    "references": {
                        "ICreateEnvelopeRecipientFromTemplate": {
                            "location": "import",
                            "path": "@verdocs/js-sdk",
                            "id": "node_modules::ICreateEnvelopeRecipientFromTemplate"
                        }
                    }
                }
            }, {
                "method": "templateUpdated",
                "name": "templateUpdated",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Event fired when the template is updated in any way. May be used for tasks such as cache invalidation or reporting to other systems."
                },
                "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": "templateCreated",
                "name": "templateCreated",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Event fired when the template is created by the upload step."
                },
                "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": "rolesUpdated",
                "name": "rolesUpdated",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Event fired when roles are updated in the roles step."
                },
                "complexType": {
                    "original": "{endpoint: VerdocsEndpoint; templateId: string; event: 'added' | 'deleted' | 'updated'; roles: IRole[]}",
                    "resolved": "{ endpoint: VerdocsEndpoint; templateId: string; event: \"added\" | \"deleted\" | \"updated\"; roles: IRole[]; }",
                    "references": {
                        "VerdocsEndpoint": {
                            "location": "import",
                            "path": "@verdocs/js-sdk",
                            "id": "node_modules::VerdocsEndpoint"
                        },
                        "IRole": {
                            "location": "import",
                            "path": "@verdocs/js-sdk",
                            "id": "node_modules::IRole"
                        }
                    }
                }
            }];
    }
    static get elementRef() { return "el"; }
    static get watchers() {
        return [{
                "propName": "templateId",
                "methodName": "onTemplateIdChanged"
            }, {
                "propName": "step",
                "methodName": "onStepChanged"
            }];
    }
}
//# sourceMappingURL=verdocs-build.js.map
