import { h, Host } from "@stencil/core";
import { getTemplate, updateTemplate, VerdocsEndpoint } from "@verdocs/js-sdk";
import { VerdocsToast } from "../../../utils/Toast";
import { SDKError } from "../../../utils/errors";
import { Store } from "../../../utils/Datastore";
const MS_PER_DAY = 24 * 60 * 60 * 1000;
/**
 * Display an edit form that allows the user to adjust a template's roles and workflow.
 */
export class VerdocsTemplateSettings {
    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.name = null;
        this.visibility = 'private';
        this.sender = 'envelope_creator';
        this.sendReminders = false;
        this.initialReminder = 0;
        this.followupReminders = 0;
        this.dirty = false;
        this.loading = true;
        this.template = null;
    }
    disconnectedCallback() {
        this.unlistenToTemplate();
    }
    async listenToTemplate() {
        console.log('[SETTINGS] Loading template', this.templateId);
        this.unlistenToTemplate();
        Store.subscribe('templates', this.templateId, () => getTemplate(this.endpoint, this.templateId), false, (template) => {
            console.log('[SETTINGS] Template Updated', template);
            this.template = template;
            this.name = template.name;
            this.visibility = template.visibility;
            this.sender = template.sender;
            this.sendReminders = template.initial_reminder !== null;
            this.initialReminder = template.initial_reminder ? Math.floor(template.initial_reminder / MS_PER_DAY) : null;
            this.followupReminders = template.followup_reminders ? Math.floor(template.followup_reminders / MS_PER_DAY) : null;
            this.dirty = false;
            this.loading = false;
        });
    }
    unlistenToTemplate() {
        if (this.templateListenerId) {
            Store.store.delListener(this.templateListenerId);
            this.templateListenerId = null;
        }
    }
    async componentWillLoad() {
        var _a, _b, _c;
        try {
            this.endpoint.loadSession();
            if (!this.templateId) {
                console.log(`[SETTINGS] Missing required template ID ${this.templateId}`);
                return;
            }
            if (!this.endpoint.session) {
                console.log('[SETTINGS] Unable to start builder session, must be authenticated');
                return;
            }
            this.listenToTemplate();
        }
        catch (e) {
            console.log('[SETTINGS] Error with preview session', 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));
        }
    }
    handleCancel() {
        var _a;
        (_a = this.exit) === null || _a === void 0 ? void 0 : _a.emit();
    }
    handleSubmit() {
        updateTemplate(this.endpoint, this.templateId, {
            name: this.name,
            visibility: this.visibility,
            sender: this.sender,
            initial_reminder: this.sendReminders ? this.initialReminder * MS_PER_DAY : null,
            followup_reminders: this.sendReminders ? this.followupReminders * MS_PER_DAY : null,
        })
            .then(template => {
            var _a, _b;
            console.log('[SETTINGS] Template Updated', template);
            this.dirty = false;
            this.name = template.name;
            this.visibility = template.visibility;
            this.sender = template.sender;
            this.sendReminders = template.initial_reminder !== null;
            this.initialReminder = template.initial_reminder ? Math.floor(template.initial_reminder / MS_PER_DAY) : null;
            this.followupReminders = template.followup_reminders ? Math.floor(template.followup_reminders / MS_PER_DAY) : null;
            (_a = this.templateUpdated) === null || _a === void 0 ? void 0 : _a.emit({ endpoint: this.endpoint, template, event: 'update' });
            (_b = this.next) === null || _b === void 0 ? void 0 : _b.emit();
        })
            .catch(e => {
            var _a, _b, _c, _d, _e;
            console.log('[SETTINGS] Error updating 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));
            VerdocsToast(((_e = (_d = e.response) === null || _d === void 0 ? void 0 : _d.data) === null || _e === void 0 ? void 0 : _e.error) || 'Error updating template, please try again later.');
        });
    }
    render() {
        if (!this.endpoint.session) {
            return (h(Host, null, h("verdocs-component-error", { message: "You must be authenticated to use this module." })));
        }
        if (this.loading || !this.template) {
            return (h(Host, { class: "loading" }, h("verdocs-loader", null)));
        }
        return (h(Host, null, h("form", { onSubmit: e => e.preventDefault(), onClick: e => e.stopPropagation(), autocomplete: "off" }, h("h5", null, "Settings"), h("div", { class: "row" }, h("verdocs-text-input", { id: "verdocs-field-name", label: "Template Name", value: this.name, autocomplete: "off", placeholder: "Template Name...", onInput: (e) => {
                this.name = e.target.value;
                this.dirty = true;
            } })), h("div", { class: "row" }, h("verdocs-select-input", { label: "Visibility", value: this.visibility, onInput: (e) => {
                this.visibility = e.target.value;
                this.dirty = true;
            }, options: [
                { value: 'private', label: 'Private' },
                { value: 'shared', label: 'Shared' },
                { value: 'public', label: 'Public' },
            ] })), h("div", { class: "row" }, h("verdocs-select-input", { label: "Owner for envelopes created from this template", value: this.sender, onInput: (e) => {
                this.sender = e.target.value;
                this.dirty = true;
            }, options: [
                { value: 'envelope_creator', label: 'Envelope Creator' },
                { value: 'template_owner', label: 'Template Owner' },
            ] })), h("div", { class: "row" }, h("label", null, "Send Reminders"), h("verdocs-switch", { checked: this.sendReminders, onCheckedChange: e => (this.sendReminders = e.detail) })), this.sendReminders && (h("div", { class: "row" }, h("verdocs-text-input", { id: "verdocs-field-name", label: "First Reminder (days)", value: String(this.initialReminder || 0), autocomplete: "off", placeholder: "Delay in days...", onInput: (e) => {
                this.initialReminder = +e.target.value;
                this.dirty = true;
            } }))), this.sendReminders && (h("div", { class: "row" }, h("verdocs-text-input", { id: "verdocs-field-name", label: "Follow-up Reminders (days)", value: String(this.followupReminders || 0), autocomplete: "off", placeholder: "Delay in days...", onInput: (e) => {
                this.followupReminders = +e.target.value;
                this.dirty = true;
            } }))), h("div", { class: "buttons" }, h("verdocs-button", { variant: "outline", label: "Cancel", size: "small", onClick: () => this.handleCancel() }), h("verdocs-button", { label: "Save", size: "small", onClick: () => this.handleSubmit(), disabled: !this.dirty })))));
    }
    static get is() { return "verdocs-template-settings"; }
    static get originalStyleUrls() {
        return {
            "$": ["verdocs-template-settings.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["verdocs-template-settings.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 {
            "name": {},
            "visibility": {},
            "sender": {},
            "sendReminders": {},
            "initialReminder": {},
            "followupReminders": {},
            "dirty": {},
            "loading": {},
            "template": {}
        };
    }
    static get events() {
        return [{
                "method": "next",
                "name": "next",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Event fired when the user clicks to proceed."
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }, {
                "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": "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": "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"
                        }
                    }
                }
            }];
    }
    static get elementRef() { return "el"; }
}
//# sourceMappingURL=verdocs-template-settings.js.map
