import { formatFullName, getEnvelope, getInPersonLink, getRecipientsWithActions, recipientCanAct, VerdocsEndpoint } from "@verdocs/js-sdk";
import { Host, h } from "@stencil/core";
// import {VerdocsToast} from '../../../utils/Toast';
import { SDKError } from "../../../utils/errors";
import { Store } from "../../../utils/Datastore";
/**
 * Displays a list of recipients with options to get in-person signing links for each one.
 */
export class VerdocsEnvelopeRecipientSummary {
    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 = '';
        /**
         * Enable or disable the Send Another button.
         */
        this.canSendAnother = true;
        /**
         * Enable or disable the View button.
         */
        this.canView = true;
        /**
         * Enable or disable the Done button.
         */
        this.canDone = true;
        this.recipientStatusIcons = [];
        this.containerId = `verdocs-status-indicator-${Math.random().toString(36).substring(2, 11)}`;
        this.gettingLinks = {};
        this.links = {};
        this.loading = true;
        this.envelope = null;
    }
    async componentWillLoad() {
        var _a, _b, _c;
        try {
            this.endpoint.loadSession();
            if (!this.envelopeId) {
                console.log(`[RECIPIENTS] Missing required envelope ID ${this.envelopeId}`);
                return;
            }
            if (!this.endpoint.session) {
                console.log('[RECIPIENTS] Unable to start session, must be authenticated');
                return;
            }
            this.listenToEnvelope();
        }
        catch (e) {
            console.log('[RECIPIENTS] 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) => {
            this.envelope = envelope;
            this.loading = false;
            this.sortEnvelopeRecipients();
        });
    }
    unlistenToEnvelope() {
        if (this.envelopeListenerId) {
            Store.store.delListener(this.envelopeListenerId);
            this.envelopeListenerId = null;
        }
    }
    sortEnvelopeRecipients() {
        var _a;
        (((_a = this.envelope) === null || _a === void 0 ? void 0 : _a.recipients) || []).sort((a, b) => {
            return a.sequence === b.sequence ? a.order - b.order : a.sequence - b.sequence;
        });
    }
    handleAnother(e) {
        var _a;
        e.preventDefault();
        (_a = this.another) === null || _a === void 0 ? void 0 : _a.emit({ envelope: this.envelope });
    }
    handleView(e) {
        var _a;
        e.preventDefault();
        (_a = this.view) === null || _a === void 0 ? void 0 : _a.emit({ envelope: this.envelope });
    }
    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 => {
            var _a;
            console.warn('[RECIPIENTS] Error copying to clipboard', e);
            (_a = this.sdkError) === null || _a === void 0 ? void 0 : _a.emit(e);
            // VerdocsToast(`Unable to copy to clipboard: ${e.message}`, {style: 'error'});
        });
    }
    getLink(recipient) {
        this.gettingLinks = { ...this.gettingLinks, [recipient.role_name]: true };
        getInPersonLink(this.endpoint, recipient.envelope_id, recipient.role_name)
            .then(response => {
            this.gettingLinks = { ...this.gettingLinks, [recipient.role_name]: false };
            this.links = { ...this.links, [recipient.role_name]: response.link };
            this.copyLink(response.link);
        })
            .catch(e => {
            var _a;
            this.gettingLinks = { ...this.gettingLinks, [recipient.role_name]: false };
            console.log('[RECIPIENTS] Error getting link', e);
            (_a = this.sdkError) === null || _a === void 0 ? void 0 : _a.emit(e);
            // VerdocsToast('Unable to get link: ' + e.message, {style: 'error'});
        });
    }
    render() {
        var _a;
        if (this.loading) {
            return h(Host, null);
        }
        return (h(Host, null, h("div", { class: "summary-content" }, h("h1", { class: "summary-title" }, "Recipient Summary"), h("div", { class: "summary-rows" }, (((_a = this.envelope) === null || _a === void 0 ? void 0 : _a.recipients) || []).map(recipient => {
            const recipientsWithActions = getRecipientsWithActions(this.envelope);
            const showLinkButton = recipientCanAct(recipient, recipientsWithActions);
            const link = this.links[recipient.role_name];
            const gettingLink = this.gettingLinks[recipient.role_name];
            const fullName = formatFullName(recipient);
            return (h("div", { class: "summary-recipient" }, h("div", { class: "role-name" }, recipient.role_name), h("div", { class: "role-details" }, h("div", { class: "role-info" }, h("div", { class: "role-full-name" }, fullName, " (", recipient.email || recipient.phone, ")"), showLinkButton && !link && h("verdocs-button", { size: "small", variant: "outline", label: "Get Link", disabled: gettingLink, onClick: () => this.getLink(recipient) })), link && (h("div", { class: "link-wrapper" }, h("div", { class: "link" }, link), h("verdocs-button", { size: "small", variant: "outline", label: "Copy", onClick: () => this.copyLink(link) }))))));
        })), (this.canSendAnother || this.canView || this.canDone) && (h("div", { class: "buttons" }, this.canSendAnother && h("verdocs-button", { size: "small", label: "Send Another", onClick: e => this.handleAnother(e) }), this.canView && h("verdocs-button", { size: "small", label: "View Now", onClick: e => this.handleView(e) }), this.canDone && h("verdocs-button", { size: "small", label: "Done", onClick: e => this.handleDone(e) }))))));
    }
    static get is() { return "verdocs-envelope-recipient-summary"; }
    static get originalStyleUrls() {
        return {
            "$": ["verdocs-envelope-recipient-summary.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["verdocs-envelope-recipient-summary.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": "''"
            },
            "canSendAnother": {
                "type": "boolean",
                "attribute": "can-send-another",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Enable or disable the Send Another button."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "true"
            },
            "canView": {
                "type": "boolean",
                "attribute": "can-view",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Enable or disable the View button."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "true"
            },
            "canDone": {
                "type": "boolean",
                "attribute": "can-done",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Enable or disable the Done button."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "true"
            }
        };
    }
    static get states() {
        return {
            "isOpen": {},
            "recipientStatusIcons": {},
            "containerId": {},
            "gettingLinks": {},
            "links": {},
            "loading": {},
            "envelope": {}
        };
    }
    static get events() {
        return [{
                "method": "another",
                "name": "another",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Event fired when the user clicks Send Another 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": "view",
                "name": "view",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Event fired when the user clicks Send Another 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": "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-summary.js.map
