'use strict';

var index = require('./index-p7cvUYAE.js');
var styledHost = require('./styled-host-Ch0-dxF-.js');
var table = require('./table-DjbNv28p.js');
var eventTypes = require('./event-types-YOY5TKUN.js');
var checkPkgVersion = require('./check-pkg-version-B9EoYyZR.js');
var parts = require('./parts-BXshb_S-.js');
var utils = require('./utils-CYONRFR6.js');
require('./config-state-BIgGhhe9.js');
var Plaid = require('./Plaid-CPESyiiV.js');
var Pagination = require('./Pagination-Dediz133.js');
require('./Business-oBifyXkW.js');
var badge = require('./badge-GBNtUypt.js');
require('./dinero-BwNN_k7x.js');
var utils$1 = require('./utils-BsnepLy6.js');
var Api = require('./Api-D9vOcUw4.js');
var Analytics = require('./Analytics-C6KBHEIP.js');
var terminalOrdersListParamsState = require('./terminal-orders-list-params-state-vGJZ6Oe2.js');
require('./spinner-C6ZGOB2P.js');
require('./package-YyJzVqrh.js');
require('./index-W-zoNiyM.js');

const MapTerminalOrderStatusToBadge = (status) => {
    const statusToBadgeProps = {
        submitted: {
            variant: badge.BadgeVariant.PRIMARY,
            title: 'This order is submitted',
            text: 'Submitted',
        },
        completed: {
            variant: badge.BadgeVariant.SUCCESS,
            title: 'This order has been completed',
            text: 'Completed',
        },
        created: {
            variant: badge.BadgeVariant.SECONDARY,
            title: 'This order is created',
            text: 'Created',
        },
        in_progress: {
            variant: badge.BadgeVariant.PRIMARY,
            title: 'This order is in progress',
            text: 'In Progress',
        },
        on_hold: {
            variant: badge.BadgeVariant.WARNING,
            title: 'This order is on hold',
            text: 'On Hold',
        },
        canceled: {
            variant: badge.BadgeVariant.DANGER,
            title: 'This order is canceled',
            text: 'Canceled',
        }
    };
    const badgeProps = statusToBadgeProps[status];
    return index.h(badge.Badge, Object.assign({}, badgeProps));
};

const defaultColumnsKeys = 'created_at,updated_at,order_status,quantity';
const terminalOrdersTableColumns = {
    created_at: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The date and time the order was created" }, "Created At")),
    updated_at: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The date and time the order was last updated" }, "Updated At")),
    order_status: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The current status of the order" }, "Order Status")),
    business_id: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The business ID associated with the order" }, "Business ID")),
    company_name: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The business name associated with the order" }, "Business Name")),
    provider: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The provider associated with the order" }, "Provider")),
    order_type: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The type of order" }, "Order Type")),
    quantity: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The number of terminals associated with the order" }, "Order Quantity")),
};
const terminalOrdersTableCells = {
    created_at: (terminalOrder, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, index.h("div", { class: "fw-bold" }, utils.convertToLocal(terminalOrder.created_at, { showDisplayDate: true })), index.h("div", { class: "fw-bold" }, utils.convertToLocal(terminalOrder.created_at, { showTime: true })))),
    updated_at: (terminalOrder, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, index.h("div", { class: "fw-bold" }, utils.convertToLocal(terminalOrder.updated_at, { showDisplayDate: true })), index.h("div", { class: "fw-bold" }, utils.convertToLocal(terminalOrder.updated_at, { showTime: true })))),
    order_status: (terminalOrder, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, MapTerminalOrderStatusToBadge(terminalOrder.order_status))),
    business_id: (terminalOrder, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, terminalOrder.business_id)),
    company_name: (terminalOrder, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, terminalOrder.company_name)),
    provider: (terminalOrder, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, terminalOrder.provider)),
    order_type: (terminalOrder, index$1) => {
        let orderType;
        if (terminalOrder.order_type === Plaid.TerminalOrderType.boardingOnly) {
            orderType = 'Boarding Only';
        }
        else if (terminalOrder.order_type === Plaid.TerminalOrderType.boardingShipping) {
            orderType = 'Boarding & Shipping';
        }
        return (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, orderType));
    },
    quantity: (terminalOrder, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, terminalOrder.terminals.length)),
};

const makeGetTerminalOrders = ({ id, authToken, service }) => async ({ params, onSuccess, onError, final }) => {
    var _a, _b;
    try {
        const response = await service.fetchTerminalOrders(id, authToken, params);
        if (!response.error) {
            const pagingInfo = Object.assign({}, response.page_info);
            const terminalOrders = ((_a = response.data) === null || _a === void 0 ? void 0 : _a.map((dataItem) => new Plaid.TerminalOrder(dataItem))) || [];
            onSuccess({ terminalOrders, pagingInfo });
        }
        else {
            const responseError = utils$1.getErrorMessage(response.error);
            const code = utils$1.getErrorCode((_b = response.error) === null || _b === void 0 ? void 0 : _b.code);
            return onError({
                error: responseError,
                code,
                severity: Plaid.ComponentErrorSeverity.ERROR,
            });
        }
    }
    catch (error) {
        const code = utils$1.getErrorCode(error === null || error === void 0 ? void 0 : error.code);
        return onError({
            error: error.message || error,
            code,
            severity: Plaid.ComponentErrorSeverity.ERROR,
        });
    }
    finally {
        final();
    }
};

const api = Api.Api();
class TerminalOrderService {
    async fetchTerminalOrders(accountId, authToken, params) {
        const endpoint = 'terminals/orders';
        const headers = { account: accountId };
        return api.get({ endpoint, params, headers, authToken });
    }
}

const JustifiTerminalOrdersList = class {
    constructor(hostRef) {
        index.registerInstance(this, hostRef);
        this.clickEvent = index.createEvent(this, "click-event", 7);
        this.errorEvent = index.createEvent(this, "error-event", 7);
        this.columns = defaultColumnsKeys;
        this.terminalOrders = [];
        this.loading = true;
        this.paging = Pagination.pagingDefaults;
        this.pagingParams = {};
        this.handleClickPrevious = (beforeCursor) => {
            this.pagingParams = { before_cursor: beforeCursor };
            this.clickEvent.emit({ name: eventTypes.TableClickActions.previous });
        };
        this.handleClickNext = (afterCursor) => {
            this.pagingParams = { after_cursor: afterCursor };
            this.clickEvent.emit({ name: eventTypes.TableClickActions.next });
        };
        this.rowClickHandler = (e) => {
            const clickedOrderId = e.target.closest('tr').dataset.rowEntityId;
            if (!clickedOrderId)
                return;
            const orderData = this.terminalOrders.find((order) => order.id === clickedOrderId);
            this.clickEvent.emit({ name: eventTypes.TableClickActions.row, data: orderData });
        };
    }
    componentWillLoad() {
        checkPkgVersion.checkPkgVersion();
        this.analytics = new Analytics.JustifiAnalytics(this);
        this.terminalOrdersTable = new table.Table(this.terminalOrders, this.columns, terminalOrdersTableColumns, terminalOrdersTableCells);
        this.initializeGetData();
        if (this.getTerminalOrders) {
            this.fetchData();
        }
        terminalOrdersListParamsState.onQueryParamsChange('set', () => {
            this.pagingParams = {};
        });
        terminalOrdersListParamsState.onQueryParamsChange('reset', () => {
            this.pagingParams = {};
            this.errorMessage = '';
        });
    }
    disconnectedCallback() {
        var _a;
        (_a = this.analytics) === null || _a === void 0 ? void 0 : _a.cleanup();
    }
    authPropChanged() {
        this.initializeGetData();
        if (this.getTerminalOrders) {
            this.fetchData();
        }
    }
    pagingOrColumnsChanged() {
        if (this.getTerminalOrders) {
            this.fetchData();
        }
    }
    initializeGetData() {
        if (this.accountId && this.authToken) {
            this.getTerminalOrders = makeGetTerminalOrders({
                id: this.accountId,
                authToken: this.authToken,
                service: new TerminalOrderService(),
            });
        }
        else {
            this.errorMessage = 'Account ID and Auth Token are required';
            this.errorEvent.emit({
                errorCode: Plaid.ComponentErrorCodes.MISSING_PROPS,
                message: this.errorMessage,
                severity: Plaid.ComponentErrorSeverity.ERROR,
            });
        }
    }
    fetchData() {
        if (!this.getTerminalOrders) {
            return;
        }
        this.loading = true;
        this.getTerminalOrders({
            params: this.terminalOrderParams,
            onSuccess: async ({ terminalOrders, pagingInfo }) => {
                this.terminalOrders = terminalOrders;
                this.paging = pagingInfo;
                this.terminalOrdersTable.collectionData = this.terminalOrders;
            },
            onError: ({ error, code, severity }) => {
                this.errorMessage = error;
                this.errorEvent.emit({
                    errorCode: code,
                    message: error,
                    severity,
                });
            },
            final: () => {
                this.loading = false;
            },
        });
    }
    get terminalOrderParams() {
        const requestParams = terminalOrdersListParamsState.getRequestParams();
        const params = Object.assign(Object.assign({}, requestParams), this.pagingParams);
        return params;
    }
    get entityId() {
        return this.terminalOrders.map((terminalOrder) => terminalOrder.id);
    }
    get showEmptyState() {
        return !this.loading && !this.errorMessage && this.terminalOrdersTable.rowData.length < 1;
    }
    get showErrorState() {
        return !this.loading && !!this.errorMessage;
    }
    get showRowData() {
        return !this.showEmptyState && !this.showErrorState && !this.loading;
    }
    render() {
        return (index.h(styledHost.StyledHost, { key: '14c0dfe45a6833251f4c2d1d27ea49568f7ac01e' }, index.h(table.TableWrapper, { key: '7995d0b2ccb002265769804aa112dca1178d14dd' }, index.h(table.TableComponent, { key: 'ddfb54945255a1ae601659b5dee46da8e7fbfb52' }, index.h(table.TableHead, { key: '26958541cd82e414d9b079ac18ff69022969a4b8' }, index.h(table.TableHeadRow, { key: '1068214ddc3e0003bab2212c0baff74c7e086b96' }, this.terminalOrdersTable.columnData.map((column) => column))), index.h(table.TableBody, { key: '7b043e72311e7c956855320b7293a33e41f08da2' }, index.h(table.TableLoadingState, { key: 'b2532063645be1e926cfd7dca5b33414d09e5703', columnSpan: this.terminalOrdersTable.columnKeys.length, isLoading: this.loading }), index.h(table.TableEmptyState, { key: 'ceec3f0f885e1377afdf36ca2714ebac9b6f7bfc', isEmpty: this.showEmptyState, columnSpan: this.terminalOrdersTable.columnKeys.length }), index.h(table.TableErrorState, { key: '2c35baac2f8902e8bf96844f17f57104ba253986', columnSpan: this.terminalOrdersTable.columnKeys.length, errorMessage: this.errorMessage }), this.showRowData &&
            this.terminalOrdersTable.rowData.map((data, index$1) => (index.h(table.TableRow, { "data-test-id": "table-row", "data-row-entity-id": this.entityId[index$1], onClick: this.rowClickHandler }, data)))), this.paging && (index.h(table.TableFoot, { key: 'f5e1fe9ba78d5cee96e044c60ffaabe45ff3d19d' }, index.h(table.TableFootRow, { key: 'ab8c1111b2a1124ba3f0b0bf2deb5893cf4c4ce5' }, index.h(table.TableFootCell, { key: 'd463b0e2db8c5d093b38816d78c9176e302fe2c0', colSpan: this.terminalOrdersTable.columnData.length }, index.h("pagination-menu", { key: '364dfccaa8480e63e51fa3bbdbf4cbb560e9fbbf', paging: Object.assign(Object.assign({}, this.paging), { handleClickPrevious: this.handleClickPrevious, handleClickNext: this.handleClickNext }) })))))))));
    }
    static get watchers() { return {
        "accountId": ["authPropChanged"],
        "authToken": ["authPropChanged"],
        "pagingParams": ["pagingOrColumnsChanged"],
        "columns": ["pagingOrColumnsChanged"]
    }; }
};

exports.justifi_terminal_orders_list = JustifiTerminalOrdersList;
