import { Host, h } from "@stencil/core";
import { getEnvelope, VerdocsEndpoint } from "@verdocs/js-sdk";
import { SDKError } from "../../../utils/errors";
import { Store } from "../../../utils/Datastore";
/**
 * Displays a single recipient from an envelope, with the opportunity to copy an in-person
 * signing link for that recipient to use.
 */
export class VerdocsEnvelopeUpdateRecipient {
    constructor() {
        this.envelopeListenerId = null;
        /**
         * The endpoint to use to communicate with Verdocs. If not set, the default endpoint will be used.
         */
        this.endpoint = VerdocsEndpoint.getDefault();
        /**
         * The envelope ID to edit.
         */
        this.envelopeId = '';
        /**
         * The role to load.
         */
        this.roleName = '';
        this.gettingLink = true;
        this.link = '';
        this.loading = true;
        this.envelope = null;
        this.originalRecipient = null;
        this.updatedRecipient = null;
    }
    async componentWillLoad() {
        var _a, _b, _c;
        try {
            this.endpoint.loadSession();
            if (!this.envelopeId) {
                console.log(`[UPDATE_RECIPIENT] Missing required envelope ID ${this.envelopeId}`);
                return;
            }
            if (!this.endpoint.session) {
                console.log('[UPDATE_RECIPIENT] Unable to start session, must be authenticated');
                return;
            }
            this.listenToEnvelope();
        }
        catch (e) {
            console.log('[UPDATE_RECIPIENT] Error loading envelope', 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.unlistenToEnvelope();
    }
    async listenToEnvelope() {
        console.log('[UPDATE_RECIPIENT] Loading envelope', this.envelopeId);
        this.unlistenToEnvelope();
        Store.subscribe('envelopes', this.envelopeId, () => getEnvelope(this.endpoint, this.envelopeId), false, (envelope) => {
            var _a;
            this.envelope = envelope;
            this.loading = false;
            const recipient = (((_a = this.envelope) === null || _a === void 0 ? void 0 : _a.recipients) || []).find(r => r.role_name === this.roleName);
            this.originalRecipient = recipient;
            this.updatedRecipient = { ...recipient };
        });
    }
    unlistenToEnvelope() {
        if (this.envelopeListenerId) {
            Store.store.delListener(this.envelopeListenerId);
            this.envelopeListenerId = null;
        }
    }
    handleSave(e) {
        var _a;
        e.preventDefault();
        (_a = this.next) === null || _a === void 0 ? void 0 : _a.emit({ action: 'save', originalRecipient: this.originalRecipient, updatedRecipient: this.updatedRecipient });
    }
    handleCancel(e) {
        var _a;
        e.preventDefault();
        (_a = this.next) === null || _a === void 0 ? void 0 : _a.emit({ action: 'cancel', originalRecipient: this.originalRecipient, updatedRecipient: this.updatedRecipient });
    }
    render() {
        if (this.loading || !this.updatedRecipient) {
            return h(Host, null);
        }
        return (h(Host, null, h("div", { class: "summary-content" }, h("h1", { class: "summary-title" }, "Update Recipient"), h("div", { class: "summary-rows" }, h("div", { class: "fields" }, h("div", { class: "role-name" }, this.updatedRecipient.role_name), h("div", { class: "field" }, h("div", { class: "fields-row" }, h("verdocs-text-input", { value: this.updatedRecipient.first_name, placeholder: "First Name...", onInput: (e) => (this.updatedRecipient.first_name = e.target.value) }), h("verdocs-text-input", { value: this.updatedRecipient.last_name, placeholder: "Last Name...", onInput: (e) => (this.updatedRecipient.last_name = e.target.value) }))), h("div", { class: "field" }, h("verdocs-text-input", { type: "email", value: this.updatedRecipient.email, placeholder: "Email Address...", onInput: (e) => (this.updatedRecipient.email = e.target.value) })), h("div", { class: "field" }, h("verdocs-text-input", { type: "tel", value: this.updatedRecipient.phone, placeholder: "Phone Number...", onInput: (e) => (this.updatedRecipient.phone = e.target.value) })), h("div", { class: "field" }, h("textarea", { id: "verdocs-contact-picker-message", name: "verdocs-contact-picker-message", "data-lpignore": "true", autocomplete: "blocked", placeholder: "Optional message to include in invitation...", onInput: (e) => (this.updatedRecipient.message = e.target.value) }, this.updatedRecipient.message)), h("div", { class: "note" }, "NOTE: If you change the recipient's email address or invite message, they will receive a new invitation to sign the envelope. This will also reset their status if they have previously declined to sign."))), h("div", { class: "buttons" }, h("verdocs-button", { variant: "outline", size: "small", label: "Cancel", onClick: e => this.handleCancel(e) }), h("verdocs-button", { size: "small", label: "Save", onClick: e => this.handleSave(e) })))));
    }
    static get is() { return "verdocs-envelope-update-recipient"; }
    static get originalStyleUrls() {
        return {
            "$": ["verdocs-envelope-update-recipient.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["verdocs-envelope-update-recipient.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()"
            },
            "envelopeId": {
                "type": "string",
                "attribute": "envelope-id",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The envelope ID to edit."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "''"
            },
            "roleName": {
                "type": "string",
                "attribute": "role-name",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The role to load."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "''"
            }
        };
    }
    static get states() {
        return {
            "isOpen": {},
            "gettingLink": {},
            "link": {},
            "loading": {},
            "envelope": {},
            "originalRecipient": {},
            "updatedRecipient": {}
        };
    }
    static get events() {
        return [{
                "method": "next",
                "name": "next",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Event fired when the user clicks Done to proceed. It is up to the host application\nto save any updates and proceed to the next step."
                },
                "complexType": {
                    "original": "{action: 'cancel' | 'save'; originalRecipient: IRecipient; updatedRecipient: IRecipient}",
                    "resolved": "{ action: \"cancel\" | \"save\"; originalRecipient: IRecipient; updatedRecipient: IRecipient; }",
                    "references": {
                        "IRecipient": {
                            "location": "import",
                            "path": "@verdocs/js-sdk",
                            "id": "node_modules::IRecipient"
                        }
                    }
                }
            }, {
                "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-envelope-update-recipient.js.map
