'use strict';

var index = require('./index-Be9PlTB7.js');
var jsSdk = require('@verdocs/js-sdk');
var utils = require('./utils-DCB8q98B.js');
var Toast = require('./Toast-CFBM1R4z.js');
var errors = require('./errors-D1XRvnet.js');
require('./_commonjsHelpers-BJu3ubxk.js');
require('./index-CeUF44L9.js');
require('./Types-RUyU-svM.js');

const verdocsEnvelopesListCss = "@-webkit-keyframes verdocs-field-pulse{0%{background-color:rgba(0, 0, 0, 0.35)}50%{background-color:rgba(0, 0, 0, 0)}100%{background-color:rgba(0, 0, 0, 0.35)}}@keyframes verdocs-field-pulse{0%{background-color:rgba(0, 0, 0, 0.35)}50%{background-color:rgba(0, 0, 0, 0)}100%{background-color:rgba(0, 0, 0, 0.35)}}verdocs-envelopes-list{display:-ms-flexbox;display:flex;padding:10px;font-size:18px;-ms-flex-wrap:nowrap;flex-wrap:nowrap;border-radius:6px;color:#33364b;-ms-flex-direction:column;flex-direction:column;font-family:\"Inter\", \"Barlow\", sans-serif}@media screen and (max-width: 800px){verdocs-envelopes-list{font-size:14px}}verdocs-envelopes-list .envelope-placeholder{height:48px;-ms-flex:0 0 48px;flex:0 0 48px;margin:5px 0;border-radius:5px;background:#f5f5fa}verdocs-envelopes-list .header{width:100%;row-gap:4px;display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;-webkit-column-gap:12px;-moz-column-gap:12px;column-gap:12px;margin:0 0 10px 0;-ms-flex-align:center;align-items:center;-ms-flex-direction:row;flex-direction:row}verdocs-envelopes-list .header .filter{width:300px}verdocs-envelopes-list .header verdocs-text-input{margin:0}verdocs-envelopes-list .header verdocs-text-input input{height:32px}verdocs-envelopes-list .filter{-ms-flex-align:center;align-items:center}verdocs-envelopes-list .envelope{width:100%;margin:3px 0;background:#ffffff}verdocs-envelopes-list .envelope:hover{cursor:pointer;background:#f5f5fa}verdocs-envelopes-list .envelope .inner{gap:12px;display:-ms-flexbox;display:flex;padding:8px 14px;border-radius:5px;-ms-flex-direction:row;flex-direction:row;-ms-flex-align:center;align-items:center;container-type:inline-size}verdocs-envelopes-list .envelope .inner svg{width:24px;height:24px}verdocs-envelopes-list .vert-spacer{height:50px;display:-ms-flexbox;display:flex;-ms-flex:0 0 1px;flex:0 0 1px;border-right:1px solid #dad8dd}@media screen and (max-width: 800px){verdocs-envelopes-list .vert-spacer{display:none}}@media screen and (max-width: 800px){verdocs-envelopes-list .envelope-icon{display:none}}@media screen and (max-width: 800px){verdocs-envelopes-list verdocs-checkbox{display:none}}verdocs-envelopes-list .last-modified{color:#444;display:-ms-flexbox;display:flex;-ms-flex:0 0 180px;flex:0 0 180px;-ms-flex-direction:row;flex-direction:row;-ms-flex-align:center;align-items:center;white-space:nowrap}@media screen and (max-width: 800px){verdocs-envelopes-list .last-modified{display:none}}verdocs-envelopes-list .envelope-name{-ms-flex:1;flex:1;display:-ms-flexbox;display:flex;color:#000000;line-height:28px;overflow:hidden;white-space:nowrap;text-overflow:ellipsis}verdocs-envelopes-list .envelope-recipients{color:#4b5563;font-weight:700;overflow:hidden;white-space:nowrap;text-overflow:ellipsis}verdocs-envelopes-list .empty-text{text-align:center;margin:16px 0 0 0;padding:80px 80px;border:2px solid #ccc}verdocs-envelopes-list .containing{gap:12px;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-direction:row;flex-direction:row}@media screen and (max-width: 800px){verdocs-envelopes-list verdocs-status-indicator{font-size:14px}}";

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' },
];
const VerdocsEnvelopesList = class {
    constructor(hostRef) {
        index.registerInstance(this, hostRef);
        this.changeView = index.createEvent(this, "changeView");
        this.changeStatus = index.createEvent(this, "changeStatus");
        this.changeSort = index.createEvent(this, "changeSort");
        this.changeMatch = index.createEvent(this, "changeMatch");
        this.sdkError = index.createEvent(this, "sdkError");
        this.viewEnvelope = index.createEvent(this, "viewEnvelope");
        this.finishEnvelope = index.createEvent(this, "finishEnvelope");
        /**
         * The endpoint to use to communicate with Verdocs. If not set, the default endpoint will be used.
         */
        this.endpoint = jsSdk.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.match.trim()) ;
            // if (this.containing.trim()) {
            //   queryParams.field_value = this.containing.trim();
            // }
            const response = await jsSdk.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 errors.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() {
        utils.saveEnvelopesAsZip(this.endpoint, this.selectedEnvelopes)
            .then(() => {
            this.selectedEnvelopes = [];
        })
            .catch(e => {
            console.log('[ENVELOPES] Download error', e);
            Toast.VerdocsToast('Download error: ' + e.message, { style: 'error' });
        });
    }
    downloadEnvelope(envelope) {
        utils.saveEnvelopesAsZip(this.endpoint, [envelope]).catch(e => {
            console.log('[ENVELOPES] Download error', e);
            Toast.VerdocsToast('Download error: ' + e.message, { style: 'error' });
        });
    }
    render() {
        return (index.h(index.Host, { key: 'cbb6106629de750aade6c39f705ecb9f9d103031' }, index.h("div", { key: '73d522c9cfa87930dcba2aeb543634580c1e76d9', class: "header" }, index.h("div", { key: 'ac4f7014544ec81be9bae96bb07fdbf7495ca705', class: "filter" }, index.h("verdocs-text-input", { key: '5b1df9e9aac89391d555eed621efb355e6bac6ce', 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);
            } })), index.h("verdocs-quick-filter", { key: 'ca081aa3b0a548620d66f49935d08430714bcd90', label: "View", value: this.view, options: ViewFilters, onOptionSelected: e => {
                this.view = e.detail.value;
            } }), this.view === 'all' && (index.h("verdocs-quick-filter", { key: '1b956dfc0c28df1b990aa695c0df8d114c6fe1b5', label: "Status", value: this.status, options: StatusFilters, onOptionSelected: e => {
                this.status = e.detail.value;
            } })), this.view === 'all' && (index.h("verdocs-quick-filter", { key: 'ea43244641ff51676c8e59346af1843582865b82', label: "Sort By", value: this.sort, options: SortFilters, onOptionSelected: e => {
                this.sort = e.detail.value;
            } })), this.loading && index.h("verdocs-spinner", { key: 'd04c29615a3e9886d9eee78eb76ad4f30ccf8cb4', mode: "dark", size: 24 }), index.h("div", { key: '8ff362b83507cf75ac48787c67b2728d7980ec59', style: { display: 'flex', flex: '1' } }), this.selectedEnvelopes.length > 0 && index.h("verdocs-button", { key: 'f786131801b4476edd8260dac6213c0bfeaaead6', label: `Download (${this.selectedEnvelopes.length})`, onClick: () => this.handleDownload() })), this.envelopes.map(envelope => {
            var _a;
            const recipientsWithActions = jsSdk.getRecipientsWithActions(envelope);
            const userCanCancel = jsSdk.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 && jsSdk.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 (index.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 }); } }, index.h("div", { class: "inner" }, index.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);
                    }
                } }), index.h("div", { class: "vert-spacer" }), index.h("span", { innerHTML: DocumentIcon, class: "envelope-icon" }), index.h("div", { class: "envelope-name" }, envelope.name, ":\u00A0 ", index.h("div", { class: "envelope-recipients" }, envelope.recipients.map(r => jsSdk.formatFullName(r)))), index.h("div", { class: "vert-spacer" }), index.h("verdocs-status-indicator", { envelope: envelope, style: { width: '125px' } }), index.h("div", { class: "vert-spacer" }), index.h("div", { class: "last-modified" }, new Date(envelope.updated_at).toLocaleString()), index.h("div", { class: "vert-spacer" }), index.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?')) {
                                jsSdk.cancelEnvelope(this.endpoint, envelope.id)
                                    .then(() => Toast.VerdocsToast('Envelope canceled'))
                                    .catch(e => Toast.VerdocsToast('Unable to cancel envelope: ' + e.messabge, { style: 'error' }));
                                this.queryEnvelopes().catch(() => { });
                            }
                            break;
                    }
                } }))));
        }), !this.initiallyLoaded && (index.h("div", { key: '4624707aa6e7a1dfda1859ac051889354ad580c1', style: { width: '100%' } }, jsSdk.integerSequence(0, this.rowsPerPage).map(() => (index.h("div", { class: "envelope-placeholder" }))))), this.initiallyLoaded && !this.envelopes.length && index.h("div", { key: '2fe7ad29dc24785c0c3985c415965855262be746', class: "empty-text" }, "No matching envelopes found. Please adjust your filters and try again."), this.initiallyLoaded && this.envelopes.length && this.showPagination ? (index.h("div", { style: { marginTop: '20px' } }, index.h("verdocs-pagination", { selectedPage: this.selectedPage, perPage: this.rowsPerPage, itemCount: this.count, onSelectPage: e => {
                this.selectedPage = e.detail.selectedPage;
            } }))) : (index.h("div", null))));
    }
    static get watchers() { return {
        "view": ["handleViewUpdated"],
        "status": ["handleStatusUpdated"],
        "sort": ["handleSortUpdated"],
        "match": ["handleMatchUpdated"],
        "selectedPage": ["handlePageUpdated"]
    }; }
};
VerdocsEnvelopesList.style = verdocsEnvelopesListCss;

exports.verdocs_envelopes_list = VerdocsEnvelopesList;
//# sourceMappingURL=verdocs-envelopes-list.entry.cjs.js.map

//# sourceMappingURL=verdocs-envelopes-list.cjs.entry.js.map