import { h } from "@stencil/core";
import { ComponentErrorCodes, ComponentErrorSeverity } from "../../api/ComponentError";
import JustifiAnalytics from "../../api/Analytics";
import { checkPkgVersion } from "../../utils/check-pkg-version";
import { TerminalService } from "../../api/services/terminal.service";
import { makeGetTerminals } from "../../actions/terminal/get-terminals";
import { SubAccountService } from "../../api/services/subaccounts.service";
import { StyledHost } from "../../ui-components";
import { defaultColumnsKeys, terminalTableColumns, terminalTableCells } from "./terminals-table";
import { makeGetSubAccounts } from "../../actions/sub-account/get-subaccounts";
import { pagingDefaults } from "../../api";
import { TableEmptyState, TableErrorState, TableLoadingState } from "../../ui-components";
import { Table } from "../../utils/table";
import { getRequestParams, onQueryParamsChange } from "./terminals-list-params-state";
import { TableWrapper, TableComponent, TableHead, TableHeadRow, TableBody, TableRow, TableFoot, TableFootRow, TableFootCell, TableClickActions } from "../../ui-components";
export class JustifiTerminalsList {
    constructor() {
        this.terminals = [];
        this.subAccounts = [];
        this.loading = true;
        this.paging = pagingDefaults;
        this.pagingParams = {};
        this.columns = defaultColumnsKeys;
        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 clickedTerminalID = e.target.closest('tr').dataset.rowEntityId;
            if (!clickedTerminalID)
                return;
            const terminalData = this.terminals.find((terminal) => terminal.id === clickedTerminalID);
            this.clickEvent.emit({ name: TableClickActions.row, data: terminalData });
        };
    }
    componentWillLoad() {
        checkPkgVersion();
        this.analytics = new JustifiAnalytics(this);
        this.terminalsTable = new Table(this.terminals, this.columns, terminalTableColumns, terminalTableCells);
        this.initializeGetData();
        if (this.getTerminals && this.getSubAccounts) {
            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();
    }
    ;
    propChanged() {
        this.initializeGetData();
    }
    updateOnPropChange() {
        this.fetchData();
    }
    initializeGetData() {
        this.initializeGetTerminals();
        this.initializeGetSubAccounts();
    }
    initializeGetTerminals() {
        if (this.accountId && this.authToken) {
            this.getTerminals = makeGetTerminals({
                id: this.accountId,
                authToken: this.authToken,
                service: new TerminalService()
            });
        }
        else {
            this.errorMessage = 'Account ID and Auth Token are required';
            this.errorEvent.emit({
                errorCode: ComponentErrorCodes.MISSING_PROPS,
                message: this.errorMessage,
                severity: ComponentErrorSeverity.ERROR,
            });
        }
    }
    initializeGetSubAccounts() {
        if (this.accountId && this.authToken) {
            this.getSubAccounts = makeGetSubAccounts({
                primaryAccountId: this.accountId,
                authToken: this.authToken,
                service: new SubAccountService()
            });
        }
    }
    fetchData() {
        this.loading = true;
        this.getTerminals({
            params: this.terminalParams,
            onSuccess: async ({ terminals, pagingInfo }) => {
                this.terminals = terminals;
                this.paging = pagingInfo;
                this.terminalsTable.collectionData = this.terminals;
                const shouldFetchSubAccounts = this.terminalsTable.columnKeys.includes('sub_account_name');
                if (shouldFetchSubAccounts) {
                    await this.fetchSubAccounts();
                }
                else {
                    this.loading = false;
                }
            },
            onError: ({ error, code, severity }) => {
                this.errorMessage = error;
                this.errorEvent.emit({
                    errorCode: code,
                    message: error,
                    severity,
                });
                this.loading = false;
            },
        });
    }
    async fetchSubAccounts() {
        this.getSubAccounts({
            params: this.subAccountParams,
            onSuccess: ({ subAccounts }) => {
                this.subAccounts = subAccounts;
                this.terminals = this.terminals.map((terminal) => {
                    var _a;
                    terminal.sub_account_name = (_a = this.subAccounts.find((subAccount) => subAccount.id === terminal.account_id)) === null || _a === void 0 ? void 0 : _a.name;
                    return terminal;
                });
                this.loading = false;
            },
            onError: ({ error, code, severity }) => {
                this.errorMessage = error;
                this.errorEvent.emit({
                    errorCode: code,
                    message: error,
                    severity,
                });
                this.loading = false;
            },
        });
    }
    get terminalParams() {
        const requestParams = getRequestParams();
        const params = Object.assign(Object.assign({}, requestParams), this.pagingParams);
        return params;
    }
    get subAccountParams() {
        const accountIdNumbers = this.terminals.map((terminal) => terminal.account_id);
        const uniqueAccountIds = [...new Set(accountIdNumbers)];
        const accountIdString = uniqueAccountIds.join(',');
        return { sub_account_id: accountIdString };
    }
    get entityId() {
        return this.terminals.map((terminal) => terminal.id);
    }
    get showEmptyState() {
        return !this.loading && !this.errorMessage && this.terminalsTable.rowData.length < 1;
    }
    get showErrorState() {
        return !this.loading && !!this.errorMessage;
    }
    get showRowData() {
        return !this.showEmptyState && !this.showErrorState && !this.loading;
    }
    render() {
        return (h(StyledHost, { key: '69c475e7a428c549a05f21bbd9bd80ce6d77836b' }, h(TableWrapper, { key: 'a3d916daff63336299366f27959b8e54134f54c5' }, h(TableComponent, { key: '412538503e7a212bd7b5723dddad82abe95fc3c2' }, h(TableHead, { key: '5501e72fd1931b1ffc17e6bf0d09d692b9cfbe17' }, h(TableHeadRow, { key: 'e0391a60a807cbdba97ef11f04275eb3072dc40c' }, this.terminalsTable.columnData.map((column) => column))), h(TableBody, { key: '56686e423499aff459fa3d6d93fae0fd7621b10b' }, h(TableLoadingState, { key: '0b70b5a0132754b1ce14e8baaeb7a9932c73b0ad', columnSpan: this.terminalsTable.columnKeys.length, isLoading: this.loading }), h(TableEmptyState, { key: '1230c30259de7ad89a1ccf1bb709db5bdda9152f', isEmpty: this.showEmptyState, columnSpan: this.terminalsTable.columnKeys.length }), h(TableErrorState, { key: 'fc5dbeae973d56980e077fa861d0bf95f282cbec', columnSpan: this.terminalsTable.columnKeys.length, errorMessage: this.errorMessage }), this.showRowData && this.terminalsTable.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: 'c68e2cb14c8fa6a56243803e440cc13388ffaaf4' }, h(TableFootRow, { key: 'bcc17671c48f5a397dff15333a49305a443aef21' }, h(TableFootCell, { key: '92a690d558b001bb346c2e17fb1e02691ec2a029', colSpan: this.terminalsTable.columnData.length }, h("pagination-menu", { key: '2a8233397675c7af4fd95df203eb4438f1c4adbd', paging: Object.assign(Object.assign({}, this.paging), { handleClickPrevious: this.handleClickPrevious, handleClickNext: this.handleClickNext }) })))))))));
    }
    static get is() { return "justifi-terminals-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 {
            "getTerminals": {},
            "getSubAccounts": {},
            "terminals": {},
            "terminalsTable": {},
            "subAccounts": {},
            "loading": {},
            "errorMessage": {},
            "paging": {},
            "pagingParams": {}
        };
    }
    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/ComponentEvents",
                            "id": "src/api/ComponentEvents.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/ComponentEvents",
                            "id": "src/api/ComponentEvents.ts::ComponentErrorEvent"
                        }
                    }
                }
            }];
    }
    static get watchers() {
        return [{
                "propName": "accountId",
                "methodName": "propChanged"
            }, {
                "propName": "authToken",
                "methodName": "propChanged"
            }, {
                "propName": "pagingParams",
                "methodName": "updateOnPropChange"
            }, {
                "propName": "getTerminals",
                "methodName": "updateOnPropChange"
            }, {
                "propName": "getSubAccounts",
                "methodName": "updateOnPropChange"
            }, {
                "propName": "columns",
                "methodName": "updateOnPropChange"
            }];
    }
}
;
