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 set of tabs for the template builder.
 */
export class VerdocsTemplateBuildTabs {
    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;
    }
    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;
        }
    }
    onTemplateIdChanged(newTemplateId) {
        console.log('[BUILD_TABS] Template ID changed', newTemplateId);
        this.listenToTemplate();
    }
    onStepChanged(newStep) {
        console.log('[BUILD_TABS] Step changed', newStep);
    }
    async componentWillLoad() {
        var _a, _b, _c;
        try {
            this.endpoint.loadSession();
            if (!this.endpoint.session) {
                console.log('[BUILD_TABS] Unable to start builder session, must be authenticated');
                return;
            }
            if (!this.templateId) {
                this.step = 'attachments';
                console.log('[BUILD_TABS] Missing required template ID, forcing view to attachments');
                return;
            }
            this.listenToTemplate();
        }
        catch (e) {
            console.log('[BUILD_TABS] 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));
        }
    }
    handleSelect(tab) {
        var _a;
        if (tab.disabled || tab.id === this.step) {
            return;
        }
        this.step = tab.id;
        (_a = this.stepChanged) === null || _a === void 0 ? void 0 : _a.emit(tab.id);
    }
    render() {
        var _a, _b, _c;
        if (this.loading) {
            return (h(Host, null, 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." })));
        }
        const canEditRoles = (((_a = this.template) === null || _a === void 0 ? void 0 : _a.documents) || []).length > 0;
        const canEditFields = canEditRoles && (((_b = this.template) === null || _b === void 0 ? void 0 : _b.roles) || []).length > 0;
        const canPreview = canEditFields && (((_c = this.template) === null || _c === void 0 ? void 0 : _c.fields) || []).length > 0;
        const tabs = [
            { id: 'attachments', label: 'Attachments', disabled: false },
            { id: 'roles', label: 'Workflow', disabled: !canEditRoles },
            { id: 'fields', label: 'Fields', disabled: !canEditFields },
            { id: 'preview', label: 'Preview & Send', disabled: !canPreview },
        ];
        return (h(Host, null, tabs.map(tab => {
            const isActive = tab.id === this.step;
            const classes = ['tab'];
            if (isActive)
                classes.push('active');
            if (tab.disabled)
                classes.push('disabled');
            return (h("div", { class: classes.join(' '), onClick: () => this.handleSelect(tab) }, h("span", null, tab.label), h("svg", { "aria-hidden": "true", xmlns: "http://www.w3.org/2000/svg", width: "19", height: "50", viewBox: "0 0 19 50" }, h("polygon", { points: "0,0 19,25 0,50", fill: isActive ? '#ffffff' : '#e7e7e7' }))));
        })));
    }
    static get is() { return "verdocs-template-build-tabs"; }
    static get originalStyleUrls() {
        return {
            "$": ["verdocs-template-build-tabs.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["verdocs-template-build-tabs.css"]
        };
    }
    static get properties() {
        return {
            "endpoint": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "VerdocsEndpoint",
                    "resolved": "VerdocsEndpoint",
                    "references": {
                        "VerdocsEndpoint": {
                            "location": "import",
                            "path": "@verdocs/js-sdk",
                            "id": "node_modules::VerdocsEndpoint",
                            "referenceLocation": "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",
                "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,
                "attribute": "template-id",
                "defaultValue": "null"
            },
            "step": {
                "type": "string",
                "mutable": true,
                "complexType": {
                    "original": "TVerdocsBuildStep",
                    "resolved": "\"attachments\" | \"fields\" | \"preview\" | \"roles\"",
                    "references": {
                        "TVerdocsBuildStep": {
                            "location": "local",
                            "path": "/Users/chad/projects/verdocs/active/web-sdk/verdocs-web-sdk/src/components/templates/verdocs-template-build-tabs/verdocs-template-build-tabs.tsx",
                            "id": "src/components/templates/verdocs-template-build-tabs/verdocs-template-build-tabs.tsx::TVerdocsBuildStep"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The step in the creation process to display."
                },
                "getter": false,
                "setter": false,
                "reflect": true,
                "attribute": "step",
                "defaultValue": "'preview'"
            }
        };
    }
    static get states() {
        return {
            "loading": {},
            "template": {}
        };
    }
    static get events() {
        return [{
                "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",
                            "referenceLocation": "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\"",
                    "references": {
                        "TVerdocsBuildStep": {
                            "location": "local",
                            "path": "/Users/chad/projects/verdocs/active/web-sdk/verdocs-web-sdk/src/components/templates/verdocs-template-build-tabs/verdocs-template-build-tabs.tsx",
                            "id": "src/components/templates/verdocs-template-build-tabs/verdocs-template-build-tabs.tsx::TVerdocsBuildStep"
                        }
                    }
                }
            }];
    }
    static get watchers() {
        return [{
                "propName": "templateId",
                "methodName": "onTemplateIdChanged"
            }, {
                "propName": "step",
                "methodName": "onStepChanged"
            }];
    }
}
//# sourceMappingURL=verdocs-template-build-tabs.js.map
