import { h, Host } from "@stencil/core";
import { deleteTemplateRole, getTemplate, isValidEmail, updateTemplateRole, VerdocsEndpoint } from "@verdocs/js-sdk";
import { SDKError } from "../../../utils/errors";
import { Store } from "../../../utils/Datastore";
const TrashIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="#a50021"><path stroke-linecap="round" stroke-linejoin="round" d="M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0" /></svg>`;
/**
 * Present an editing form suitable for adjusting template-role properties.
 */
export class VerdocsTemplateRoleProperties {
    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 = '';
        /**
         * The role name to edit.
         */
        this.roleName = '';
        this.dirty = false;
        this.saving = false;
        this.name = '';
        this.type = 'signer';
        this.first_name = '';
        this.last_name = '';
        this.email = '';
        this.phone = '';
        this.delegator = false;
        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('[ROLES 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));
        }
    }
    disconnectedCallback() {
        this.unlistenToTemplate();
    }
    async listenToTemplate() {
        console.log('[ROLES] Loading tempate', this.templateId);
        this.unlistenToTemplate();
        Store.subscribe('templates', this.templateId, () => getTemplate(this.endpoint, this.templateId), false, (template) => {
            var _a;
            console.log('[BUILD] Template Updated', template);
            this.template = template;
            this.loading = false;
            const editingRole = (_a = this.template) === null || _a === void 0 ? void 0 : _a.roles.find(role => role.name === this.roleName);
            if (editingRole) {
                this.name = editingRole.name;
                this.type = editingRole.type;
                this.first_name = editingRole.first_name;
                this.last_name = editingRole.last_name;
                this.email = editingRole.email;
                this.phone = editingRole.phone;
                this.delegator = editingRole.delegator;
                console.log('[ROLES] Editing role', editingRole);
            }
        });
    }
    unlistenToTemplate() {
        if (this.templateListenerId) {
            Store.store.delListener(this.templateListenerId);
            this.templateListenerId = null;
        }
    }
    handleCancel(e) {
        var _a, _b;
        e.stopPropagation();
        const editingRole = (_a = this.template) === null || _a === void 0 ? void 0 : _a.roles.find(role => role.name === this.roleName);
        if (editingRole) {
            this.name = editingRole.name;
            this.type = editingRole.type;
            this.first_name = editingRole.first_name;
            this.last_name = editingRole.last_name;
            this.email = editingRole.email;
            this.phone = editingRole.phone;
            this.delegator = editingRole.delegator;
        }
        this.dirty = false;
        (_b = this.close) === null || _b === void 0 ? void 0 : _b.emit();
    }
    async handleSave(e) {
        e.stopPropagation();
        this.saving = true;
        updateTemplateRole(this.endpoint, this.templateId, this.roleName, {
            name: this.name,
            type: this.type,
            first_name: this.first_name,
            last_name: this.last_name,
            email: this.email,
            phone: this.phone,
            delegator: this.delegator,
        })
            .then(async (r) => {
            var _a;
            console.log('[ROLES] Update result', r);
            this.saving = false;
            this.dirty = false;
            const newTemplate = JSON.parse(JSON.stringify(this.template));
            const roleIndex = newTemplate.roles.findIndex(role => role.name === this.roleName);
            if (roleIndex > -1) {
                newTemplate.roles[roleIndex] = r;
            }
            Store.updateTemplate(this.templateId, newTemplate);
            (_a = this.close) === null || _a === void 0 ? void 0 : _a.emit();
        })
            .catch(e => {
            console.log('[ROLES Update error', e);
            this.saving = false;
        });
    }
    async handleDelete(e) {
        e.stopPropagation();
        if (window.confirm('Are you sure you wish to remove this role? All associated fields will be removed as well. This action cannot be undone.')) {
            deleteTemplateRole(this.endpoint, this.templateId, this.roleName)
                .then(() => {
                var _a, _b;
                const newTemplate = JSON.parse(JSON.stringify(this.template));
                newTemplate.roles = newTemplate.roles.filter(role => role.name !== this.roleName);
                Store.getTemplate(this.endpoint, this.templateId, true);
                // Store.updateTemplate(this.templateId, newTemplate);
                (_a = this.delete) === null || _a === void 0 ? void 0 : _a.emit({ templateId: this.templateId, roleName: this.roleName });
                (_b = this.close) === null || _b === void 0 ? void 0 : _b.emit();
            })
                .catch(e => {
                console.log('[ROLES Deletion error', e);
            });
        }
    }
    render() {
        var _a;
        const hasFields = (((_a = this.template) === null || _a === void 0 ? void 0 : _a.fields) || []).some(field => field.role_name === this.roleName);
        // Either all three should be empty, or all three need to be filled
        const isValid = (!this.email && !this.first_name && !this.last_name) || (isValidEmail(this.email) && !!this.first_name && !!this.last_name);
        return (h(Host, { key: '14d2d9bb4253201a9cb659c6637960194dc7d134' }, h("form", { key: '09d0a10f48c8f4ca3f6b679d09c3c71ea0c0cdb9', onSubmit: e => e.preventDefault(), onClick: e => e.stopPropagation(), autocomplete: "off" }, h("div", { key: 'b65e74e82bb7689d706ba0e56521d04fe01ae057' }, h("verdocs-text-input", { key: 'c7e3da4d57b096f71a4c5e49948ee0a4e0594e0c', id: "verdocs-role-name", label: "Role Name (Must be unique)", value: this.name, autocomplete: "off", disabled: hasFields, placeholder: "Role Name...", onInput: (e) => {
                this.name = e.target.value;
                this.dirty = true;
            } }), hasFields && h("div", { key: '9a80102f0a04118069c2865c9295e5da3914b381', class: "instructions" }, "This role has fields assigned and can no longer be renamed.")), h("div", { key: '93ca24cfbc2b1f8e729c30a0726b14091695ba92' }, h("div", { key: '0b5eeeab4aad7e1659581eb8c17e14012d79b5e6', class: "input-label" }, "Type:"), h("verdocs-select-input", { key: '883b1456bad033a17023559a210f61efc17cb1ab', value: this.type, options: [
                { label: 'Signer', value: 'signer' },
                { label: 'CC', value: 'cc' },
                { label: 'Approver', value: 'approver' },
            ], onInput: (e) => {
                this.type = e.target.value;
                this.dirty = true;
            } })), h("div", { key: 'fec29a6add9ab2a60e4deb29ee77c851973e0517' }, h("div", { key: 'a18a7d1edfb673e382d76d04d833f3daf28ca26f', class: "input-label" }, "Default Contact Info:"), h("div", { key: '1206cab495d52ab12428dbc346126df3a2aa9c1a', class: "first-last" }, h("verdocs-text-input", { key: 'aa4433e84dee223043c49235c8e9feb7569707e9', id: "verdocs-recipient-first", value: this.first_name, autocomplete: "off", placeholder: "First...", onInput: (e) => {
                this.first_name = e.target.value;
                this.dirty = true;
            } }), h("verdocs-text-input", { key: 'b8c1069666a4674faff0c1b72bc988cf3ed3ca9b', id: "verdocs-recipient-first", value: this.last_name, autocomplete: "off", placeholder: "Last...", onInput: (e) => {
                this.last_name = e.target.value;
                this.dirty = true;
            } }))), h("div", { key: '5ea9ada6f0dac2a52b78946275603e2c99887666' }, h("verdocs-text-input", { key: '767135ec9d13ae00e6c1d259a6d53fbf85caeedd', id: "verdocs-recipient-email", value: this.email, autocomplete: "off", placeholder: "Email Address...", onInput: (e) => {
                this.email = e.target.value;
                this.dirty = true;
            } }), h("div", { key: '0c4ffc5553a054ae331bcbf48a7b702d0fd5a81e', style: { height: '15px' } }), h("div", { key: '17815735c29adc551f65a7f29d1a791c9260edfc' }, h("verdocs-text-input", { key: '0d41ae8e9cda72d881791df7d63f89f25d08da5e', id: "verdocs-recipient-phone", value: this.phone, autocomplete: "off",
            // helpText="The recipient's phone number, if it will always stay the same. Leave blank to supply this value later, when each new envelope is created from the template."
            placeholder: "Phone Number...", onInput: (e) => {
                this.phone = e.target.value;
                this.dirty = true;
            } }))), h("div", { key: 'be29c3c856e62cab357391146485230461e6c5c9', class: "buttons" }, h("button", { key: 'a714765b9f8f524a0c6573653b6ba6a59661b4d2', class: "delete-button", disabled: this.dirty, onClick: e => this.handleDelete(e), innerHTML: TrashIcon }), h("div", { key: 'aae4bf7f4fa5fc685ace057a2312461a7cf993f3', style: { flex: '1' } }), h("verdocs-button", { key: '027aa0723fc32b4713e7a9cb33e6a1b7d4b5ab18', size: "small", label: "Save", disabled: !this.dirty || !isValid, onClick: e => this.handleSave(e) })))));
    }
    static get is() { return "verdocs-template-role-properties"; }
    static get originalStyleUrls() {
        return {
            "$": ["verdocs-template-role-properties.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["verdocs-template-role-properties.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"
                        }
                    }
                },
                "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": 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,
                "attribute": "template-id",
                "defaultValue": "''"
            },
            "roleName": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The role name to edit."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "role-name",
                "defaultValue": "''"
            }
        };
    }
    static get states() {
        return {
            "dirty": {},
            "saving": {},
            "name": {},
            "type": {},
            "first_name": {},
            "last_name": {},
            "email": {},
            "phone": {},
            "delegator": {},
            "loading": {},
            "template": {}
        };
    }
    static get events() {
        return [{
                "method": "close",
                "name": "close",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Event fired when the user cancels the dialog."
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }, {
                "method": "delete",
                "name": "delete",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Event fired when the user deletes the role. The parent should update its UI to reflect the removal. When this event is emitted,\nthe role will have already been deleted server-side."
                },
                "complexType": {
                    "original": "{templateId: string; roleName: string}",
                    "resolved": "{ templateId: string; roleName: string; }",
                    "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"
                        }
                    }
                }
            }];
    }
}
//# sourceMappingURL=verdocs-template-role-properties.js.map
