import { h, proxyCustomElement, HTMLElement, createEvent } from '@stencil/core/internal/client';
import { r as Terminal, C as ComponentErrorSeverity, a as ComponentErrorCodes } from './Plaid.js';
import { J as JustifiAnalytics } from './Analytics.js';
import { c as checkPkgVersion } from './check-pkg-version.js';
import { T as TerminalService } from './terminal.service.js';
import './config-state.js';
import './dinero.js';
import { p as pagingDefaults } from './Pagination.js';
import './Business.js';
import './ApplePay.js';
import { g as getErrorCode, a as getErrorMessage } from './utils3.js';
import { m as makeGetSubAccounts, S as SubAccountService } from './get-subaccounts.js';
import { S as StyledHost } from './styled-host.js';
import './justifi-details2.js';
import { T as Table, a as TableWrapper, b as TableComponent, c as TableHead, d as TableHeadRow, e as TableBody, f as TableLoadingState, g as TableEmptyState, h as TableErrorState, i as TableRow, j as TableFoot, k as TableFootRow, l as TableFootCell } from './table.js';
import { T as TableClickActions } from './event-types.js';
import './justifi-radio-list-item2.js';
import { B as Badge, a as BadgeVariant } from './badge.js';
import { D as tableHeadCell, ah as getAlternateTableCellPart } from './parts.js';
import { l as capitalFirstLetter } from './utils2.js';
import { o as onQueryParamsChange, g as getRequestParams } from './terminals-list-params-state.js';
import { d as defineCustomElement$2 } from './pagination-menu2.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 Terminal(dataItem))) || [];
            onSuccess({ terminals, pagingInfo });
        }
        else {
            const responseError = getErrorMessage(response.error);
            const code = getErrorCode((_b = response.error) === null || _b === void 0 ? void 0 : _b.code);
            return onError({
                error: responseError,
                code,
                severity: ComponentErrorSeverity.ERROR,
            });
        }
    }
    catch (error) {
        const code = getErrorCode(error === null || error === void 0 ? void 0 : error.code);
        return onError({
            error: error.message || error,
            code,
            severity: ComponentErrorSeverity.ERROR,
        });
    }
};

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

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

const JustifiTerminalsList$1 = /*@__PURE__*/ proxyCustomElement(class JustifiTerminalsList extends HTMLElement {
    constructor(registerHost) {
        super();
        if (registerHost !== false) {
            this.__registerHost();
        }
        this.__attachShadow();
        this.clickEvent = createEvent(this, "click-event", 7);
        this.errorEvent = createEvent(this, "error-event", 7);
        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 watchers() { return {
        "accountId": ["propChanged"],
        "authToken": ["propChanged"],
        "pagingParams": ["updateOnPropChange"],
        "getTerminals": ["updateOnPropChange"],
        "getSubAccounts": ["updateOnPropChange"],
        "columns": ["updateOnPropChange"]
    }; }
}, [257, "justifi-terminals-list", {
        "accountId": [1, "account-id"],
        "authToken": [1, "auth-token"],
        "columns": [1],
        "getTerminals": [32],
        "getSubAccounts": [32],
        "terminals": [32],
        "terminalsTable": [32],
        "subAccounts": [32],
        "loading": [32],
        "errorMessage": [32],
        "paging": [32],
        "pagingParams": [32]
    }, undefined, {
        "accountId": ["propChanged"],
        "authToken": ["propChanged"],
        "pagingParams": ["updateOnPropChange"],
        "getTerminals": ["updateOnPropChange"],
        "getSubAccounts": ["updateOnPropChange"],
        "columns": ["updateOnPropChange"]
    }]);
function defineCustomElement$1() {
    if (typeof customElements === "undefined") {
        return;
    }
    const components = ["justifi-terminals-list", "pagination-menu"];
    components.forEach(tagName => { switch (tagName) {
        case "justifi-terminals-list":
            if (!customElements.get(tagName)) {
                customElements.define(tagName, JustifiTerminalsList$1);
            }
            break;
        case "pagination-menu":
            if (!customElements.get(tagName)) {
                defineCustomElement$2();
            }
            break;
    } });
}
defineCustomElement$1();

const JustifiTerminalsList = JustifiTerminalsList$1;
const defineCustomElement = defineCustomElement$1;

export { JustifiTerminalsList, defineCustomElement };
