import { Host, h } from "@stencil/core";
import { formatFullName, getEnvelope, getInPersonLink, VerdocsEndpoint } from "@verdocs/js-sdk";
import { VerdocsToast } from "../../../utils/Toast";
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 VerdocsEnvelopeRecipientLink {
    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.recipient = null;
    }
    async componentWillLoad() {
        var _a, _b, _c;
        try {
            this.endpoint.loadSession();
            if (!this.envelopeId) {
                console.log(`[RECIPIENT_LINK] Missing required envelope ID ${this.envelopeId}`);
                return;
            }
            if (!this.endpoint.session) {
                console.log('[RECIPIENT_LINK] Unable to start session, must be authenticated');
                return;
            }
            this.listenToEnvelope();
        }
        catch (e) {
            console.log('[RECIPIENT_LINK] 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('[SIDEBAR] 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;
            this.recipient = (((_a = this.envelope) === null || _a === void 0 ? void 0 : _a.recipients) || []).find(r => r.role_name === this.roleName);
            this.getLink(this.recipient);
        });
    }
    unlistenToEnvelope() {
        if (this.envelopeListenerId) {
            Store.store.delListener(this.envelopeListenerId);
            this.envelopeListenerId = null;
        }
    }
    handleDone(e) {
        var _a;
        e.preventDefault();
        (_a = this.next) === null || _a === void 0 ? void 0 : _a.emit({ envelope: this.envelope });
    }
    copyLink(link) {
        navigator.clipboard
            .writeText(link)
            .then(() => VerdocsToast('Link copied to clipboard!', { style: 'success', duration: 3000 }))
            .catch(e => {
            console.warn('[RECIPIENT_LINK] Error copying to clipboard', e);
            VerdocsToast(`Unable to copy to clipboard: ${e.message}`, { style: 'error' });
        });
    }
    getLink(recipient) {
        this.gettingLink = true;
        getInPersonLink(this.endpoint, recipient.envelope_id, recipient.role_name)
            .then(response => {
            this.gettingLink = false;
            this.link = response.link;
            // NOTE: Left here for documentation purposes. We don't auto-copy the link because many browsers now
            // error on that because we aren't the focus/gesture-initiator since we're a new component just being
            // drawn in the DOM. So we let the user click to trigger that.
            // this.copyLink(response.link);
        })
            .catch(e => {
            this.gettingLink = false;
            console.log('[RECIPIENT_LINK] Error getting link', e);
            VerdocsToast('Unable to get link: ' + e.message, { style: 'error' });
        });
    }
    render() {
        if (this.loading || !this.recipient) {
            return h(Host, null);
        }
        // const recipientsWithActions = getRecipientsWithActions(this.store.state); const showLinkButton = recipientCanAct(recipient, recipientsWithActions); const link =
        //   this.links[recipient.role_name]; const gettingLink = this.gettingLinks[recipient.role_name]; return (
        const fullName = formatFullName(this.recipient);
        return (h(Host, null, h("div", { class: "summary-content" }, h("h1", { class: "summary-title" }, "In-Person Signing Link"), h("div", { class: "summary-rows" }, h("div", { class: "summary-recipient" }, h("div", { class: "role-name" }, this.recipient.role_name), h("div", { class: "role-details" }, h("div", { class: "role-info" }, h("div", { class: "role-full-name" }, fullName, " (", this.recipient.email || this.recipient.phone, ")"), !this.link && (h("verdocs-button", { size: "small", variant: "outline", label: this.gettingLink ? 'Loading...' : 'Get Link', disabled: this.gettingLink, onClick: () => this.getLink(this.recipient) }))), this.link && (h("div", { class: "link-wrapper" }, h("div", { class: "link" }, this.link), h("verdocs-button", { size: "small", variant: "outline", label: "Copy", onClick: () => this.copyLink(this.link) })))))), h("div", { class: "buttons" }, h("verdocs-button", { size: "small", label: "Done", onClick: e => this.handleDone(e) })))));
    }
    static get is() { return "verdocs-envelope-recipient-link"; }
    static get originalStyleUrls() {
        return {
            "$": ["verdocs-envelope-recipient-link.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["verdocs-envelope-recipient-link.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": {},
            "recipient": {}
        };
    }
    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 redirect the user to the appropriate next workflow step."
                },
                "complexType": {
                    "original": "{envelope: IEnvelope}",
                    "resolved": "{ envelope: IEnvelope; }",
                    "references": {
                        "IEnvelope": {
                            "location": "import",
                            "path": "@verdocs/js-sdk",
                            "id": "node_modules::IEnvelope"
                        }
                    }
                }
            }, {
                "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-recipient-link.js.map
