import { h } from "@stencil/core";
import { StyledHost } from "../../ui-components";
import { checkPkgVersion } from "../../utils/check-pkg-version";
import { defaultColumnsKeys, terminalOrdersTableCells, terminalOrdersTableColumns, } from "./terminal-orders-table";
import { makeGetTerminalOrders } from "../../actions/terminal/get-terminal-orders";
import { TerminalOrderService } from "../../api/services/terminal_orders.service";
import { ComponentErrorCodes, ComponentErrorSeverity } from "../../api";
import JustifiAnalytics from "../../api/Analytics";
import { Table } from "../../utils/table";
import { TableEmptyState, TableErrorState, TableLoadingState } from "../../ui-components";
import { pagingDefaults } from "../../api";
import { getRequestParams, onQueryParamsChange } from "./terminal-orders-list-params-state";
import { TableWrapper, TableComponent, TableHead, TableHeadRow, TableBody, TableRow, TableFoot, TableFootRow, TableFootCell, TableClickActions, } from "../../ui-components";
export class JustifiTerminalOrdersList {
    constructor() {
        this.columns = defaultColumnsKeys;
        this.terminalOrders = [];
        this.loading = true;
        this.paging = pagingDefaults;
        this.pagingParams = {};
        this.handleClickPrevious = (beforeCursor) => {
            this.pagingParams = { before_cursor: beforeCursor };
            this.clickEvent.emit({ name: TableClickActions.previous });
        };
        this.handleClickNext = (afterCursor) => {
            this.pagingParams = { after_cursor: afterCursor };
            this.clickEvent.emit({ name: 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: TableClickActions.row, data: orderData });
        };
    }
    componentWillLoad() {
        checkPkgVersion();
        this.analytics = new JustifiAnalytics(this);
        this.terminalOrdersTable = new Table(this.terminalOrders, this.columns, terminalOrdersTableColumns, terminalOrdersTableCells);
        this.initializeGetData();
        if (this.getTerminalOrders) {
            this.fetchData();
        }
        onQueryParamsChange('set', () => {
            this.pagingParams = {};
        });
        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: ComponentErrorCodes.MISSING_PROPS,
                message: this.errorMessage,
                severity: 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 = 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 (h(StyledHost, { key: '14c0dfe45a6833251f4c2d1d27ea49568f7ac01e' }, h(TableWrapper, { key: '7995d0b2ccb002265769804aa112dca1178d14dd' }, h(TableComponent, { key: 'ddfb54945255a1ae601659b5dee46da8e7fbfb52' }, h(TableHead, { key: '26958541cd82e414d9b079ac18ff69022969a4b8' }, h(TableHeadRow, { key: '1068214ddc3e0003bab2212c0baff74c7e086b96' }, this.terminalOrdersTable.columnData.map((column) => column))), h(TableBody, { key: '7b043e72311e7c956855320b7293a33e41f08da2' }, h(TableLoadingState, { key: 'b2532063645be1e926cfd7dca5b33414d09e5703', columnSpan: this.terminalOrdersTable.columnKeys.length, isLoading: this.loading }), h(TableEmptyState, { key: 'ceec3f0f885e1377afdf36ca2714ebac9b6f7bfc', isEmpty: this.showEmptyState, columnSpan: this.terminalOrdersTable.columnKeys.length }), h(TableErrorState, { key: '2c35baac2f8902e8bf96844f17f57104ba253986', columnSpan: this.terminalOrdersTable.columnKeys.length, errorMessage: this.errorMessage }), this.showRowData &&
            this.terminalOrdersTable.rowData.map((data, index) => (h(TableRow, { "data-test-id": "table-row", "data-row-entity-id": this.entityId[index], onClick: this.rowClickHandler }, data)))), this.paging && (h(TableFoot, { key: 'f5e1fe9ba78d5cee96e044c60ffaabe45ff3d19d' }, h(TableFootRow, { key: 'ab8c1111b2a1124ba3f0b0bf2deb5893cf4c4ce5' }, h(TableFootCell, { key: 'd463b0e2db8c5d093b38816d78c9176e302fe2c0', colSpan: this.terminalOrdersTable.columnData.length }, h("pagination-menu", { key: '364dfccaa8480e63e51fa3bbdbf4cbb560e9fbbf', paging: Object.assign(Object.assign({}, this.paging), { handleClickPrevious: this.handleClickPrevious, handleClickNext: this.handleClickNext }) })))))))));
    }
    static get is() { return "justifi-terminal-orders-list"; }
    static get encapsulation() { return "shadow"; }
    static get properties() {
        return {
            "accountId": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": true,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "account-id"
            },
            "authToken": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": true,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "auth-token"
            },
            "columns": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "columns",
                "defaultValue": "defaultColumnsKeys"
            }
        };
    }
    static get states() {
        return {
            "terminalOrders": {},
            "terminalOrdersTable": {},
            "loading": {},
            "errorMessage": {},
            "paging": {},
            "pagingParams": {},
            "getTerminalOrders": {}
        };
    }
    static get events() {
        return [{
                "method": "clickEvent",
                "name": "click-event",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "ComponentClickEvent",
                    "resolved": "ComponentClickEvent",
                    "references": {
                        "ComponentClickEvent": {
                            "location": "import",
                            "path": "../../api",
                            "id": "src/api/index.ts::ComponentClickEvent"
                        }
                    }
                }
            }, {
                "method": "errorEvent",
                "name": "error-event",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "ComponentErrorEvent",
                    "resolved": "ComponentErrorEvent",
                    "references": {
                        "ComponentErrorEvent": {
                            "location": "import",
                            "path": "../../api",
                            "id": "src/api/index.ts::ComponentErrorEvent"
                        }
                    }
                }
            }];
    }
    static get watchers() {
        return [{
                "propName": "accountId",
                "methodName": "authPropChanged"
            }, {
                "propName": "authToken",
                "methodName": "authPropChanged"
            }, {
                "propName": "pagingParams",
                "methodName": "pagingOrColumnsChanged"
            }, {
                "propName": "columns",
                "methodName": "pagingOrColumnsChanged"
            }];
    }
}
