'use strict';

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

const makeGetTerminals = ({ id, authToken, service }) => async ({ params, onSuccess, onError }) => {
    var _a, _b;
    try {
        const response = await service.fetchTerminals(id, authToken, params);
        if (!response.error) {
            const pagingInfo = Object.assign({}, response.page_info);
            const terminals = ((_a = response.data) === null || _a === void 0 ? void 0 : _a.map((dataItem) => new Plaid.Terminal(dataItem))) || [];
            onSuccess({ terminals, pagingInfo });
        }
        else {
            const responseError = utils.getErrorMessage(response.error);
            const code = utils.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.getErrorCode(error === null || error === void 0 ? void 0 : error.code);
        return onError({
            error: error.message || error,
            code,
            severity: Plaid.ComponentErrorSeverity.ERROR,
        });
    }
};

const MapTerminalStatusToBadge = (status) => {
    const statusToBadgeProps = {
        connected: {
            variant: badge.BadgeVariant.SUCCESS,
            title: 'This terminal is connected',
            text: 'Connected',
        },
        disconnected: {
            variant: badge.BadgeVariant.DANGER,
            title: 'This terminal is disconnected',
            text: 'Disconnected',
        },
        unknown: {
            variant: badge.BadgeVariant.SECONDARY,
            title: 'The status of this terminal is unknown',
            text: 'Unknown',
        },
        pending_configuration: {
            variant: badge.BadgeVariant.WARNING,
            title: 'This terminal is pending configuration',
            text: 'Pending configuration',
        },
        archived: {
            variant: badge.BadgeVariant.SECONDARY,
            title: 'This terminal is archived',
            text: 'Archived',
        }
    };
    const badgeProps = statusToBadgeProps[status];
    return index.h(badge.Badge, Object.assign({}, badgeProps));
};

const defaultColumnsKeys = 'nickname,provider_serial_number,status';
const terminalTableColumns = {
    nickname: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The nickname associated with the terminal" }, "Nickname")),
    model_name: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The model name of the terminal" }, "Model Name")),
    id: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The ID of the terminal" }, "ID")),
    provider: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The provider of the terminal" }, "Provider")),
    provider_serial_number: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The serial number of the terminal" }, "Serial Number")),
    device_id: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The device/provider ID of the terminal" }, "Device ID")),
    sub_account_name: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The sub account associated with the terminal" }, "Sub Account")),
    status: () => (index.h("th", { part: parts.tableHeadCell, scope: "col", title: "The current status of each terminal" }, "Status")),
};
const terminalTableCells = {
    nickname: (terminal, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, terminal.nickname)),
    model_name: (terminal, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, terminal.model_name)),
    id: (terminal, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, terminal.id)),
    provider: (terminal, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, utils$1.capitalFirstLetter(terminal.provider))),
    provider_serial_number: (terminal, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, terminal.provider_serial_number)),
    device_id: (terminal, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, terminal.provider_id)),
    sub_account_name: (terminal, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, terminal.sub_account_name)),
    status: (terminal, index$1) => (index.h("td", { part: parts.getAlternateTableCellPart(index$1) }, MapTerminalStatusToBadge(terminal.status))),
};

const JustifiTerminalsList = class {
    constructor(hostRef) {
        index.registerInstance(this, hostRef);
        this.clickEvent = index.createEvent(this, "click-event", 7);
        this.errorEvent = index.createEvent(this, "error-event", 7);
        this.terminals = [];
        this.subAccounts = [];
        this.loading = true;
        this.paging = Pagination.pagingDefaults;
        this.pagingParams = {};
        this.columns = defaultColumnsKeys;
        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 clickedTerminalID = e.target.closest('tr').dataset.rowEntityId;
            if (!clickedTerminalID)
                return;
            const terminalData = this.terminals.find((terminal) => terminal.id === clickedTerminalID);
            this.clickEvent.emit({ name: eventTypes.TableClickActions.row, data: terminalData });
        };
    }
    componentWillLoad() {
        checkPkgVersion.checkPkgVersion();
        this.analytics = new Analytics.JustifiAnalytics(this);
        this.terminalsTable = new table.Table(this.terminals, this.columns, terminalTableColumns, terminalTableCells);
        this.initializeGetData();
        if (this.getTerminals && this.getSubAccounts) {
            this.fetchData();
        }
        terminalsListParamsState.onQueryParamsChange('set', () => {
            this.pagingParams = {};
        });
        terminalsListParamsState.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 terminal_service.TerminalService()
            });
        }
        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,
            });
        }
    }
    initializeGetSubAccounts() {
        if (this.accountId && this.authToken) {
            this.getSubAccounts = getSubaccounts.makeGetSubAccounts({
                primaryAccountId: this.accountId,
                authToken: this.authToken,
                service: new getSubaccounts.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 = terminalsListParamsState.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 (index.h(styledHost.StyledHost, { key: '69c475e7a428c549a05f21bbd9bd80ce6d77836b' }, index.h(table.TableWrapper, { key: 'a3d916daff63336299366f27959b8e54134f54c5' }, index.h(table.TableComponent, { key: '412538503e7a212bd7b5723dddad82abe95fc3c2' }, index.h(table.TableHead, { key: '5501e72fd1931b1ffc17e6bf0d09d692b9cfbe17' }, index.h(table.TableHeadRow, { key: 'e0391a60a807cbdba97ef11f04275eb3072dc40c' }, this.terminalsTable.columnData.map((column) => column))), index.h(table.TableBody, { key: '56686e423499aff459fa3d6d93fae0fd7621b10b' }, index.h(table.TableLoadingState, { key: '0b70b5a0132754b1ce14e8baaeb7a9932c73b0ad', columnSpan: this.terminalsTable.columnKeys.length, isLoading: this.loading }), index.h(table.TableEmptyState, { key: '1230c30259de7ad89a1ccf1bb709db5bdda9152f', isEmpty: this.showEmptyState, columnSpan: this.terminalsTable.columnKeys.length }), index.h(table.TableErrorState, { key: 'fc5dbeae973d56980e077fa861d0bf95f282cbec', columnSpan: this.terminalsTable.columnKeys.length, errorMessage: this.errorMessage }), this.showRowData && this.terminalsTable.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: 'c68e2cb14c8fa6a56243803e440cc13388ffaaf4' }, index.h(table.TableFootRow, { key: 'bcc17671c48f5a397dff15333a49305a443aef21' }, index.h(table.TableFootCell, { key: '92a690d558b001bb346c2e17fb1e02691ec2a029', colSpan: this.terminalsTable.columnData.length }, index.h("pagination-menu", { key: '2a8233397675c7af4fd95df203eb4438f1c4adbd', paging: Object.assign(Object.assign({}, this.paging), { handleClickPrevious: this.handleClickPrevious, handleClickNext: this.handleClickNext }) })))))))));
    }
    static get watchers() { return {
        "accountId": ["propChanged"],
        "authToken": ["propChanged"],
        "pagingParams": ["updateOnPropChange"],
        "getTerminals": ["updateOnPropChange"],
        "getSubAccounts": ["updateOnPropChange"],
        "columns": ["updateOnPropChange"]
    }; }
};

exports.justifi_terminals_list = JustifiTerminalsList;
