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: '0b632e1d433b8c0e9bb36508e6d005d4539af00f' }, h("form", { key: 'de3f838a9871a668c0c162c7ca4379aa937a149e', onSubmit: e => e.preventDefault(), onClick: e => e.stopPropagation(), autocomplete: "off" }, h("div", { key: 'ae5ef95a62f5fe7980ff77eeb2268ad4a2b179bb' }, h("verdocs-text-input", { key: '5b9338cd1dc88ff075783997670b33d491a663a7', 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: '005409c2ad6334d93b2fd7be76404b3c1ba6124a', class: "instructions" }, "This role has fields assigned and can no longer be renamed.")), h("div", { key: '18034e9ae1db939114fa94b09bb9f328df21aacf' }, h("div", { key: 'baa0d2af362729252c8c5d80726470e788ba8a96', class: "input-label" }, "Type:"), h("verdocs-select-input", { key: '5c8de343dba32e3d480e2a76217696cec67e07b9', 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: '4da5d13ecd9f31a03803e03d673a2606953d0a23' }, h("div", { key: 'f89b346b0396cfe24b8de09f3242f8cc693cf562', class: "input-label" }, "Default Contact Info:"), h("div", { key: '7341562ad13ab09f76aa9c30efcff139ee8c102e', class: "first-last" }, h("verdocs-text-input", { key: '027b6687cb31c70dda9139abd1f07ab9e0121538', 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: 'af5460024536a3bcfd5d557b16db6f4b1caaf756', 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: 'eea4aaae1ed24607c9126133aaaf2797a10b6c74' }, h("verdocs-text-input", { key: '11b86028a868937710a11f796880aea7160d4cf1', 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: '10fb85ec06d593b331b3cdd86ffce189a8b9dcf6', style: { height: '15px' } }), h("div", { key: '7c498785230b998343d1fc0f8072186df64674fb' }, h("verdocs-text-input", { key: 'dc6fb97cb2c151ab0c9756743c3141573c55a8e8', 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: '69a3f2441823debc162e29aa17476cedbc09a154', class: "buttons" }, h("button", { key: '3bc722b9cb95d670ff8f92ae4e381251f5c22346', class: "delete-button", disabled: this.dirty, onClick: e => this.handleDelete(e), innerHTML: TrashIcon }), h("div", { key: '4fdae55a5ff51377d0f49e1091cef5274ba0485e', style: { flex: '1' } }), h("verdocs-button", { key: 'fc9f540fcc1dc9b31cba805a765ffbe37d69bbd5', 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
