import { Host, h } from "@stencil/core";
import { userCanCancelEnvelope, userCanAct, cancelEnvelope, integerSequence, formatFullName } from "@verdocs/js-sdk";
import { VerdocsEndpoint, getEnvelopes, getRecipientsWithActions } from "@verdocs/js-sdk";
import { saveEnvelopesAsZip } from "../../../utils/utils";
import { VerdocsToast } from "../../../utils/Toast";
import { SDKError } from "../../../utils/errors";
const DocumentIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" stroke="#000000" viewBox="0 0 24 24" stroke-width="1.5"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12h3.75M9 15h3.75M9 18h3.75m3 .75H18a2.25 2.25 0 002.25-2.25V6.108c0-1.135-.845-2.098-1.976-2.192a48.424 48.424 0 00-1.123-.08m-5.801 0c-.065.21-.1.433-.1.664 0 .414.336.75.75.75h4.5a.75.75 0 00.75-.75 2.25 2.25 0 00-.1-.664m-5.8 0A2.251 2.251 0 0113.5 2.25H15c1.012 0 1.867.668 2.15 1.586m-5.8 0c-.376.023-.75.05-1.124.08C9.095 4.01 8.25 4.973 8.25 6.108V8.25m0 0H4.875c-.621 0-1.125.504-1.125 1.125v11.25c0 .621.504 1.125 1.125 1.125h9.75c.621 0 1.125-.504 1.125-1.125V9.375c0-.621-.504-1.125-1.125-1.125H8.25zM6.75 12h.008v.008H6.75V12zm0 3h.008v.008H6.75V15zm0 3h.008v.008H6.75V18z" /></svg>`;
const ViewFilters = [
    { value: 'all', label: 'All' },
    { value: 'inbox', label: 'Inbox' },
    { value: 'sent', label: 'Sent' },
    { value: 'completed', label: 'Completed' },
    { value: 'action', label: 'Action Required' },
    { value: 'waiting', label: 'Waiting on Others' },
];
const StatusFilters = [
    { value: 'all', label: 'All' },
    { value: 'pending', label: 'Pending' },
    { value: 'in progress', label: 'In Progress' },
    { value: 'complete', label: 'Completed' },
    { value: 'declined', label: 'Declined' },
    { value: 'canceled', label: 'Canceled' },
];
const SortFilters = [
    { value: 'created_at', label: 'Created' },
    { value: 'updated_at', label: 'Updated' },
    { value: 'canceled_at', label: 'Canceled' },
    { value: 'envelope_name', label: 'Name' },
    { value: 'envelope_status', label: 'Status' },
];
/**
 * Displays a list of envelopes matching specified conditions.
 */
export class VerdocsEnvelopesList {
    constructor() {
        /**
         * The endpoint to use to communicate with Verdocs. If not set, the default endpoint will be used.
         */
        this.endpoint = VerdocsEndpoint.getDefault();
        /**
         * The filtered view to display. "completed" will show envelopes that have been submitted. "action" will
         * show envelopes where the user is a recipient and the envelope is not completed. "waiting" will show
         * only envelopes where the user is the sender and the envelope is not completed.
         */
        this.view = undefined;
        /**
         * The status value to filter by
         */
        this.status = 'all';
        /**
         * The sort field to use
         */
        this.sort = 'created_at';
        /**
         * If set, filter envelopes by the specified string.
         */
        this.match = '';
        /**
         * If set, filter envelopes by the specified "containing" value.
         */
        // @Prop({reflect: true, mutable: true}) containing: string = '';
        /**
         * Whether or not pagination should be enabled.
         */
        this.showPagination = true;
        /**
         * The number of rows to display per page.
         */
        this.rowsPerPage = 10;
        /**
         * The initial page number to select. Pagination is internally controlled but may be overriden by the
         * host applicaiton.
         */
        this.selectedPage = 0;
        this.count = 0;
        this.initiallyLoaded = false;
        this.loading = true;
        this.selectedEnvelopes = [];
        this.envelopes = [];
    }
    handleViewUpdated() {
        return this.queryEnvelopes();
    }
    handleStatusUpdated() {
        return this.queryEnvelopes();
    }
    handleSortUpdated() {
        return this.queryEnvelopes();
    }
    handleMatchUpdated() {
        return this.queryEnvelopes();
    }
    // @Watch('containing')
    // handleContainingUpdated() {
    //   return this.queryEnvelopes();
    // }
    handlePageUpdated() {
        return this.queryEnvelopes();
    }
    componentWillLoad() {
        this.endpoint.onSessionChanged((_, session, profile) => {
            console.log('[ENVELOPES_LIST] onSessionChanged', session, profile);
        });
        this.endpoint.loadSession();
    }
    async componentDidLoad() {
        await this.queryEnvelopes();
        this.initiallyLoaded = true;
    }
    async queryEnvelopes() {
        var _a, _b, _c;
        try {
            this.loading = true;
            let queryParams = {
                page: this.selectedPage,
                // sort: this.sort,
                rows: this.rowsPerPage,
            };
            switch (this.view) {
                case 'all':
                    queryParams = {
                        ...queryParams,
                        // sort: this.sort,
                        // direction: this.sort === 'name' ? 'asc' : 'desc',
                        status: (this.status === 'all' ? ['pending', 'in progress', 'complete', 'declined', 'canceled'] : [this.status]),
                    };
                    break;
                case 'inbox':
                    queryParams = {
                        ...queryParams,
                        // is_recipient: true,
                        // sort: 'updated_at',
                        // recipient_status: ['invited', 'declined', 'opened', 'signed', 'submitted', 'canceled'],
                    };
                    break;
                case 'sent':
                    queryParams = {
                        ...queryParams,
                        // FIXME
                        // is_owner: true,
                        // sort: 'updated_at',
                    };
                    break;
                case 'action':
                    queryParams = {
                        ...queryParams,
                        // sort: 'updated_at',
                        // is_recipient: true,
                        status: ['pending', 'in progress'],
                        // recipient_status: ['invited', 'opened', 'signed'],
                    };
                    break;
                case 'waiting':
                    queryParams = {
                        ...queryParams,
                        // FIXME
                        // is_owner: true,
                        // sort: 'updated_at',
                        // direction: 'desc',
                        status: ['pending', 'in progress'],
                    };
                    break;
                case 'completed':
                    queryParams = {
                        ...queryParams,
                        // sort: 'updated_at',
                        // direction: 'desc',
                        status: ['complete'],
                    };
                    break;
                default:
                    queryParams = {
                        ...queryParams,
                        // sort: 'updated_at',
                        // direction: 'desc',
                        status: (this.status === 'all' ? ['pending', 'in progress', 'complete', 'declined', 'canceled'] : [this.status]),
                    };
            }
            // These filters should only be applied in "View All" mode. Otherwise the user could have set them to something
            // then changed the view e.g. to Inbox and the filter could break the view (e.g. View:Inbox, Status:Declined
            // would never return anything).
            if (this.view === 'all') {
                if (this.status !== 'all') {
                    queryParams.status = [this.status];
                }
            }
            if (this.sort !== 'updated_at') {
                // queryParams.sort = this.sort;
                // queryParams.direction = this.sort === 'name' ? 'asc' : 'desc';
            }
            if (this.match.trim()) {
                // queryParams.match = this.match.trim();
            }
            // if (this.containing.trim()) {
            //   queryParams.field_value = this.containing.trim();
            // }
            const response = await getEnvelopes(this.endpoint, queryParams);
            this.envelopes = response.envelopes;
            this.count = response.count;
            this.loading = false;
        }
        catch (e) {
            this.loading = false;
            console.log('[ENVELOPES] Error listing envelopes', 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));
        }
    }
    handleDownload() {
        saveEnvelopesAsZip(this.endpoint, this.selectedEnvelopes)
            .then(() => {
            this.selectedEnvelopes = [];
        })
            .catch(e => {
            console.log('[ENVELOPES] Download error', e);
            VerdocsToast('Download error: ' + e.message, { style: 'error' });
        });
    }
    downloadEnvelope(envelope) {
        saveEnvelopesAsZip(this.endpoint, [envelope]).catch(e => {
            console.log('[ENVELOPES] Download error', e);
            VerdocsToast('Download error: ' + e.message, { style: 'error' });
        });
    }
    render() {
        return (h(Host, { key: 'c164108740fe2979d49969cff9309faa8c76ab39' }, h("div", { key: '89ea7a2cfba74a5efc723b11b85ce73c42785260', class: "header" }, h("div", { key: '22d68c923c0904c6b5374fa4ddea39428de3cadc', class: "filter" }, h("verdocs-text-input", { key: '82e396b43330b174d708732c22a384cdd5bf710a', id: "verdocs-filter-name", value: this.match, clearable: true, autocomplete: "off", placeholder: "Filter by Name, Recipient, or Field...", onFocusout: (e) => {
                var _a;
                // We don't locally filter envelopes because there are too many fields to match against efficiently.
                this.match = e.target.value.trim();
                (_a = this.changeMatch) === null || _a === void 0 ? void 0 : _a.emit(this.match);
            } })), h("verdocs-quick-filter", { key: '721393026ba97346a14c0622dbc667ad20e612ba', label: "View", value: this.view, options: ViewFilters, onOptionSelected: e => {
                this.view = e.detail.value;
            } }), this.view === 'all' && (h("verdocs-quick-filter", { key: '78c069f98e70644dcbd9a03b1dfe512774d424a2', label: "Status", value: this.status, options: StatusFilters, onOptionSelected: e => {
                this.status = e.detail.value;
            } })), this.view === 'all' && (h("verdocs-quick-filter", { key: '83df69798d32972d3d48951a283aa7893bde24d1', label: "Sort By", value: this.sort, options: SortFilters, onOptionSelected: e => {
                this.sort = e.detail.value;
            } })), this.loading && h("verdocs-spinner", { key: '7a4613ec8b94abdd9679bec26ee131e33ce307b5', mode: "dark", size: 24 }), h("div", { key: '7438d9a6484afae3e64ff9f2b949e0b306a0311b', style: { display: 'flex', flex: '1' } }), this.selectedEnvelopes.length > 0 && h("verdocs-button", { key: '984dd9ff7e43b4d9c2f01c7a5effe096a47aa8e5', label: `Download (${this.selectedEnvelopes.length})`, onClick: () => this.handleDownload() })), this.envelopes.map(envelope => {
            var _a;
            const recipientsWithActions = getRecipientsWithActions(envelope);
            const userCanCancel = userCanCancelEnvelope(this.endpoint.profile, envelope);
            const userRole = recipientsWithActions.find(recipient => { var _a; return recipient.email === ((_a = this.endpoint.session) === null || _a === void 0 ? void 0 : _a.email) || ''; });
            const userCanFinish = userRole && userCanCancel && userCanAct(((_a = this.endpoint.session) === null || _a === void 0 ? void 0 : _a.email) || '', recipientsWithActions);
            const menuOptions = [
                { label: 'View Envelope', id: 'view' },
                { label: 'Finish Envelope', id: 'finish', disabled: !userCanFinish },
                { label: 'Download', id: 'download' },
                { label: 'Cancel', id: 'cancel', disabled: !userCanCancel },
            ];
            return (h("div", { class: "envelope", key: envelope.id, onClick: () => { var _a; return (_a = this.viewEnvelope) === null || _a === void 0 ? void 0 : _a.emit({ endpoint: this.endpoint, envelope }); } }, h("div", { class: "inner" }, h("verdocs-checkbox", { checked: this.selectedEnvelopes.findIndex(e => e.id === envelope.id) !== -1, onClick: e => e.stopPropagation(), onInput: (e) => {
                    if (e.target.checked) {
                        this.selectedEnvelopes = [...this.selectedEnvelopes, envelope];
                    }
                    else {
                        this.selectedEnvelopes = this.selectedEnvelopes.filter(e => e.id !== envelope.id);
                    }
                } }), h("div", { class: "vert-spacer" }), h("span", { innerHTML: DocumentIcon, class: "envelope-icon" }), h("div", { class: "envelope-name" }, envelope.name, ":\u00A0 ", h("div", { class: "envelope-recipients" }, envelope.recipients.map(r => formatFullName(r)))), h("div", { class: "vert-spacer" }), h("verdocs-status-indicator", { envelope: envelope, style: { width: '125px' } }), h("div", { class: "vert-spacer" }), h("div", { class: "last-modified" }, new Date(envelope.updated_at).toLocaleString()), h("div", { class: "vert-spacer" }), h("verdocs-dropdown", { options: menuOptions, onOptionSelected: e => {
                    var _a, _b;
                    switch (e.detail.id) {
                        case 'view':
                            (_a = this.viewEnvelope) === null || _a === void 0 ? void 0 : _a.emit({ endpoint: this.endpoint, envelope });
                            break;
                        case 'finish':
                            (_b = this.finishEnvelope) === null || _b === void 0 ? void 0 : _b.emit({ endpoint: this.endpoint, envelope });
                            break;
                        case 'download':
                            this.downloadEnvelope(envelope);
                            break;
                        case 'cancel':
                            if (window.confirm('Are you sure you want to cancel this envelope?')) {
                                cancelEnvelope(this.endpoint, envelope.id)
                                    .then(() => VerdocsToast('Envelope canceled'))
                                    .catch(e => VerdocsToast('Unable to cancel envelope: ' + e.messabge, { style: 'error' }));
                                this.queryEnvelopes().catch(() => { });
                            }
                            break;
                    }
                } }))));
        }), !this.initiallyLoaded && (h("div", { key: '6cf4b54bdbbfcf76849de4cd9a42eb05babcdfc8', style: { width: '100%' } }, integerSequence(0, this.rowsPerPage).map(() => (h("div", { class: "envelope-placeholder" }))))), this.initiallyLoaded && !this.envelopes.length && h("div", { key: '19f5866766130424f3eb6944cd61904f509d3f71', class: "empty-text" }, "No matching envelopes found. Please adjust your filters and try again."), this.initiallyLoaded && this.envelopes.length && this.showPagination ? (h("div", { style: { marginTop: '20px' } }, h("verdocs-pagination", { selectedPage: this.selectedPage, perPage: this.rowsPerPage, itemCount: this.count, onSelectPage: e => {
                this.selectedPage = e.detail.selectedPage;
            } }))) : (h("div", null))));
    }
    static get is() { return "verdocs-envelopes-list"; }
    static get originalStyleUrls() {
        return {
            "$": ["verdocs-envelopes-list.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["verdocs-envelopes-list.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()"
            },
            "view": {
                "type": "string",
                "attribute": "view",
                "mutable": true,
                "complexType": {
                    "original": "'all' | 'inbox' | 'sent' | 'completed' | 'action' | 'waiting'",
                    "resolved": "\"action\" | \"all\" | \"completed\" | \"inbox\" | \"sent\" | \"waiting\"",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "The filtered view to display. \"completed\" will show envelopes that have been submitted. \"action\" will\nshow envelopes where the user is a recipient and the envelope is not completed. \"waiting\" will show\nonly envelopes where the user is the sender and the envelope is not completed."
                },
                "getter": false,
                "setter": false,
                "reflect": true,
                "defaultValue": "undefined"
            },
            "status": {
                "type": "string",
                "attribute": "status",
                "mutable": true,
                "complexType": {
                    "original": "TEnvelopeStatus | 'all'",
                    "resolved": "\"all\" | \"canceled\" | \"complete\" | \"declined\" | \"in progress\" | \"pending\"",
                    "references": {
                        "TEnvelopeStatus": {
                            "location": "import",
                            "path": "@verdocs/js-sdk",
                            "id": "node_modules::TEnvelopeStatus"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The status value to filter by"
                },
                "getter": false,
                "setter": false,
                "reflect": true,
                "defaultValue": "'all'"
            },
            "sort": {
                "type": "string",
                "attribute": "sort",
                "mutable": true,
                "complexType": {
                    "original": "'name' | 'created_at' | 'updated_at' | 'canceled_at' | 'status'",
                    "resolved": "\"canceled_at\" | \"created_at\" | \"name\" | \"status\" | \"updated_at\"",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The sort field to use"
                },
                "getter": false,
                "setter": false,
                "reflect": true,
                "defaultValue": "'created_at'"
            },
            "match": {
                "type": "string",
                "attribute": "match",
                "mutable": true,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "If set, filter envelopes by the specified string."
                },
                "getter": false,
                "setter": false,
                "reflect": true,
                "defaultValue": "''"
            },
            "showPagination": {
                "type": "boolean",
                "attribute": "show-pagination",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Whether or not pagination should be enabled."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "true"
            },
            "rowsPerPage": {
                "type": "number",
                "attribute": "rows-per-page",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The number of rows to display per page."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "10"
            },
            "selectedPage": {
                "type": "number",
                "attribute": "selected-page",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The initial page number to select. Pagination is internally controlled but may be overriden by the\nhost applicaiton."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "0"
            }
        };
    }
    static get states() {
        return {
            "count": {},
            "initiallyLoaded": {},
            "loading": {},
            "selectedEnvelopes": {},
            "envelopes": {}
        };
    }
    static get events() {
        return [{
                "method": "changeView",
                "name": "changeView",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Event fired when the user changes their view. Host applications can use this to save the user's preferences."
                },
                "complexType": {
                    "original": "'all' | 'inbox' | 'sent' | 'completed' | 'action' | 'waiting'",
                    "resolved": "\"action\" | \"all\" | \"completed\" | \"inbox\" | \"sent\" | \"waiting\"",
                    "references": {}
                }
            }, {
                "method": "changeStatus",
                "name": "changeStatus",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Event fired when the user changes their status filter. Host applications can use this to save the user's preferences."
                },
                "complexType": {
                    "original": "TEnvelopeStatus | 'all'",
                    "resolved": "\"all\" | \"canceled\" | \"complete\" | \"declined\" | \"in progress\" | \"pending\"",
                    "references": {
                        "TEnvelopeStatus": {
                            "location": "import",
                            "path": "@verdocs/js-sdk",
                            "id": "node_modules::TEnvelopeStatus"
                        }
                    }
                }
            }, {
                "method": "changeSort",
                "name": "changeSort",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Event fired when the user changes their sort order. Host applications can use this to save the user's preferences."
                },
                "complexType": {
                    "original": "'name' | 'created_at' | 'updated_at' | 'canceled_at' | 'status'",
                    "resolved": "\"canceled_at\" | \"created_at\" | \"name\" | \"status\" | \"updated_at\"",
                    "references": {}
                }
            }, {
                "method": "changeMatch",
                "name": "changeMatch",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Event fired when the user changes the match filter. This is fired for every inputChange event (every character\ntyped). This event is provided for balance with the other events, but host applications should generally not\nsave this value. Users might appreciate applications remembering their sorting or filtering preferences, but\nprobably not their search terms."
                },
                "complexType": {
                    "original": "string",
                    "resolved": "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"
                        }
                    }
                }
            }, {
                "method": "viewEnvelope",
                "name": "viewEnvelope",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Event fired when the user clicks an activity entry. Typically the host application will use this to navigate\nto the envelope detail view."
                },
                "complexType": {
                    "original": "{endpoint: VerdocsEndpoint; envelope: IEnvelope}",
                    "resolved": "{ endpoint: VerdocsEndpoint; envelope: IEnvelope; }",
                    "references": {
                        "VerdocsEndpoint": {
                            "location": "import",
                            "path": "@verdocs/js-sdk",
                            "id": "node_modules::VerdocsEndpoint"
                        },
                        "IEnvelope": {
                            "location": "import",
                            "path": "@verdocs/js-sdk",
                            "id": "node_modules::IEnvelope"
                        }
                    }
                }
            }, {
                "method": "finishEnvelope",
                "name": "finishEnvelope",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Event fired when the user clicks to finish the envelope."
                },
                "complexType": {
                    "original": "{endpoint: VerdocsEndpoint; envelope: IEnvelope}",
                    "resolved": "{ endpoint: VerdocsEndpoint; envelope: IEnvelope; }",
                    "references": {
                        "VerdocsEndpoint": {
                            "location": "import",
                            "path": "@verdocs/js-sdk",
                            "id": "node_modules::VerdocsEndpoint"
                        },
                        "IEnvelope": {
                            "location": "import",
                            "path": "@verdocs/js-sdk",
                            "id": "node_modules::IEnvelope"
                        }
                    }
                }
            }];
    }
    static get watchers() {
        return [{
                "propName": "view",
                "methodName": "handleViewUpdated"
            }, {
                "propName": "status",
                "methodName": "handleStatusUpdated"
            }, {
                "propName": "sort",
                "methodName": "handleSortUpdated"
            }, {
                "propName": "match",
                "methodName": "handleMatchUpdated"
            }, {
                "propName": "selectedPage",
                "methodName": "handlePageUpdated"
            }];
    }
}
//# sourceMappingURL=verdocs-envelopes-list.js.map
