var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s)
        if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
            t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
import { h, Host } from "@stencil/core";
import classNames from "classnames";
import { trackComponent } from "../../global/utils/tracking";
import { isNestedInIfxComponent } from "../../global/utils/dom-utils";
import { detectFramework } from "../../global/utils/framework-detection";
import { createGrid } from "ag-grid-community";
import { ButtonCellRenderer } from "./buttonCellRenderer";
import { CheckboxCellRenderer } from "./checkboxCellRenderer";
import { CheckboxHeaderRenderer } from "./checkboxHeaderRenderer";
import { IconButtonCellRenderer } from "./iconButtonCellRenderer";
import { LinkCellRenderer } from "./linkCellRenderer";
import { StatusCellRenderer } from "./statusCellRenderer";
import { CustomNoRowsOverlay } from "./customNoRowsOverlay";
import { CustomLoadingOverlay } from "./customLoadingOverlay";
export class Table {
    constructor() {
        this.currentPage = 1;
        this.rowData = [];
        this.colData = [];
        this.filterOptions = {};
        this.currentFilters = {};
        this.allRowData = [];
        this.rowHeight = 'default';
        this.tableHeight = 'auto';
        this.pagination = true;
        this.paginationPageSize = 10;
        this.filterOrientation = 'sidebar';
        this.headline = '';
        this.showSidebarFilters = true;
        this.matchingResultsCount = 0;
        this.variant = 'default';
        this.serverSidePagination = false;
        this.enableSelection = false;
        this.selectedRows = new Set();
        this.selectAll = false;
        this.selectedRowsData = new Map();
        this.showLoading = false;
        this.originalRowData = [];
        this.internalItemsPerPage = JSON.stringify([
            { value: 10, label: '10', selected: true },
            { value: 20, label: '20', selected: false },
            { value: 30, label: '30', selected: false },
        ]);
        this.handleSelectAll = (checked) => {
            this.selectAll = checked;
            const newSelectedRows = new Set(this.selectedRows);
            const newSelectedRowsData = new Map(this.selectedRowsData);
            if (checked) {
                if (this.serverSidePagination) {
                    this.rowData.forEach(row => {
                        const rowId = row.__rowId;
                        newSelectedRows.add(rowId);
                        const { __checkbox, __rowId } = row, cleanRow = __rest(row, ["__checkbox", "__rowId"]);
                        newSelectedRowsData.set(rowId, cleanRow);
                    });
                }
                else {
                    this.allRowData.forEach(row => {
                        const rowId = row.__rowId;
                        newSelectedRows.add(rowId);
                        const { __checkbox, __rowId } = row, cleanRow = __rest(row, ["__checkbox", "__rowId"]);
                        newSelectedRowsData.set(rowId, cleanRow);
                    });
                }
            }
            else {
                if (this.serverSidePagination) {
                    this.rowData.forEach(row => {
                        const rowId = row.__rowId;
                        newSelectedRows.delete(rowId);
                        newSelectedRowsData.delete(rowId);
                    });
                }
                else {
                    newSelectedRows.clear();
                    newSelectedRowsData.clear();
                }
            }
            this.selectedRows = newSelectedRows;
            this.selectedRowsData = newSelectedRowsData;
            this.updateCheckboxStates();
            this.updateHeaderCheckboxState();
            this.emitSelectionChange();
        };
        this.handleRowCheckboxClick = (params) => {
            const clickedRowData = params.data;
            const rowId = clickedRowData.__rowId;
            const newSelectedRows = new Set(this.selectedRows);
            const newSelectedRowsData = new Map(this.selectedRowsData);
            if (newSelectedRows.has(rowId)) {
                newSelectedRows.delete(rowId);
                newSelectedRowsData.delete(rowId);
            }
            else {
                newSelectedRows.add(rowId);
                const { __checkbox, __rowId } = clickedRowData, cleanRow = __rest(clickedRowData, ["__checkbox", "__rowId"]);
                newSelectedRowsData.set(rowId, cleanRow);
            }
            this.selectedRows = newSelectedRows;
            this.selectedRowsData = newSelectedRowsData;
            if (this.serverSidePagination) {
                const currentPageSelectedCount = this.rowData.filter(row => newSelectedRows.has(row.__rowId)).length;
                this.selectAll = currentPageSelectedCount === this.rowData.length && this.rowData.length > 0;
            }
            else {
                this.selectAll = newSelectedRows.size === this.allRowData.length && this.allRowData.length > 0;
            }
            this.updateCheckboxStates();
            this.updateHeaderCheckboxState();
            this.emitSelectionChange();
        };
    }
    rowsChanged(_newVal) {
        const parsed = this.parseArrayInput(this.rows);
        parsed.forEach((row, index) => {
            if (!row.__rowId) {
                row.__rowId = `row_${index}_${Date.now()}_${Math.random()}`;
            }
        });
        if (this.enableSelection) {
            parsed.forEach(row => {
                var _a;
                row.__checkbox = {
                    disabled: false,
                    checked: ((_a = this.selectedRows) === null || _a === void 0 ? void 0 : _a.has(row.__rowId)) || false,
                    size: 's',
                    indeterminate: false,
                    error: false,
                };
            });
        }
        this.currentFilters = {};
        this.currentPage = 1;
        this.originalRowData = [...parsed];
        this.allRowData = [...parsed];
        this.matchingResultsCount = this.allRowData.length;
        this.updateTableView();
        this.updateFilterOptions();
    }
    colsChanged(_newVal) {
        this.colData = this.getColData();
        if (this.gridApi) {
            this.gridApi.setGridOption('columnDefs', this.colData);
            this.gridApi.sizeColumnsToFit({
                defaultMinWidth: 100,
            });
        }
        this.updateFilterOptions();
    }
    handleResultsPerPageChange(e) {
        this.paginationPageSize = Number(e.detail);
        this.currentPage = 1;
        this.updateTableView();
    }
    handleChipChange(event) {
        const { name, currentSelection, previousSelection } = event.detail;
        if (currentSelection && previousSelection) {
            // Clone the current filters state
            const updatedFilters = Object.assign({}, this.currentFilters);
            if (currentSelection.length === 0) {
                // If there are no selections for this filter, delete the filter
                delete updatedFilters[name];
                // Emit event with specific filter name
                const customEvent = new CustomEvent('ifxUpdateSidebarFilter', { detail: { filterName: name }, bubbles: true, composed: true });
                this.host.dispatchEvent(customEvent);
            }
            else {
                // Otherwise, update the filter values with the current selection
                updatedFilters[name].filterValues = currentSelection.map(selection => selection.value);
            }
            // Update the component's filters
            this.currentFilters = updatedFilters;
            // Ensure table data is updated
            this.allRowData = this.applyAllFilters(this.originalRowData, this.currentFilters);
            this.updateTableView();
        }
    }
    onButtonRendererOptionsChanged() {
        this.colData = this.getColData();
        if (this.gridApi) {
            this.gridApi.setColumnDefs(this.colData);
        }
    }
    onIconButtonRendererOptionsChanged() {
        this.colData = this.getColData();
        if (this.gridApi) {
            this.gridApi.setColumnDefs(this.colData);
        }
    }
    onCheckboxRendererOptionsChanged() {
        this.colData = this.getColData();
        if (this.gridApi) {
            this.gridApi.setColumnDefs(this.colData);
        }
    }
    parseArrayInput(input) {
        if (typeof input === 'string') {
            try {
                const parsed = JSON.parse(input);
                return Array.isArray(parsed) ? parsed : [];
            }
            catch (_a) {
                console.error('Failed to parse input:', input);
                return [];
            }
        }
        if (Array.isArray(input))
            return input;
        if (typeof input === 'object' && input !== null)
            return [input];
        return [];
    }
    toggleSidebarFilters() {
        this.showSidebarFilters = !this.showSidebarFilters;
    }
    updateFilterOptions() {
        const options = {};
        for (let col of this.colData) {
            options[col.field] = [...new Set(this.rowData.map(row => row[col.field]))];
        }
        this.filterOptions = options;
    }
    updateHeaderCheckboxState() {
        if (this.gridApi && this.enableSelection) {
            setTimeout(() => {
                var _a;
                const headerCheckbox = (_a = this.container) === null || _a === void 0 ? void 0 : _a.querySelector('.ag-header-cell[col-id="__checkbox"] ifx-checkbox');
                if (headerCheckbox) {
                    if (this.serverSidePagination) {
                        const currentPageSelectedCount = this.rowData.filter(row => this.selectedRows.has(row.__rowId)).length;
                        const allOnPageSelected = currentPageSelectedCount === this.rowData.length && this.rowData.length > 0;
                        const someOnPageSelected = currentPageSelectedCount > 0 && currentPageSelectedCount < this.rowData.length;
                        headerCheckbox.checked = allOnPageSelected;
                        headerCheckbox.indeterminate = someOnPageSelected;
                    }
                    else {
                        const allSelected = this.selectedRows.size === this.allRowData.length && this.allRowData.length > 0;
                        const someSelected = this.selectedRows.size > 0 && this.selectedRows.size < this.allRowData.length;
                        headerCheckbox.checked = allSelected;
                        headerCheckbox.indeterminate = someSelected;
                    }
                }
            }, 0);
        }
    }
    handleSidebarFilterChange(event) {
        const filterGroups = event.detail;
        const updatedFilters = {};
        filterGroups.forEach(filterGroup => {
            const filterName = filterGroup.filterGroupName;
            let filterValues;
            let type;
            if (filterGroup.selectedItems && filterGroup.selectedItems.length > 0) {
                filterValues = filterGroup.selectedItems.map(item => item.label);
                type = 'multi-select';
            }
            else if (filterGroup.value) {
                filterValues = [filterGroup.value];
                type = 'text';
            }
            else {
                filterValues = [];
            }
            if (!(filterValues.length === 0 || (filterValues.length === 1 && type === 'text' && filterValues[0] === ''))) {
                updatedFilters[filterName] = { filterValues, type };
            }
        });
        this.allRowData = this.applyAllFilters(this.originalRowData, updatedFilters);
        this.updateTableView();
        this.currentFilters = updatedFilters;
    }
    handleTopbarFilterChange(event) {
        const filters = event.detail;
        // Start by resetting the filter conditions to a blank object
        this.currentFilters = {};
        // Loop through each filter group provided in the event detail
        filters.forEach(filter => {
            const filterName = filter.filterName;
            let filterValues;
            let type = filter.type;
            if (type === 'text') {
                // Search/Text filter
                filterValues = filter.filterValues;
            }
            else {
                // Multi-select/Single-Select
                filterValues = filter.filterValues.map(item => item.label);
            }
            // If there are no filter values, or the filter is a text filter with an empty value, remove the filter
            if (!(filterValues.length === 0 || (filterValues.length === 1 && type === 'text' && filterValues[0] === ''))) {
                // Add or update the filter in the currentFilters object
                this.currentFilters[filterName] = { filterValues, type };
            }
        });
        // Now that the currentFilters object has been updated, apply all filters to the data
        this.allRowData = this.applyAllFilters(this.originalRowData, this.currentFilters);
        // After filtering, update the table view with the new filtered data
        this.updateTableView();
    }
    applyAllFilters(data, filters) {
        return data.filter(row => {
            for (const filterName in filters) {
                const filterInfo = filters[filterName];
                let selectedValues = (filterInfo.filterValues || []).map(value => {
                    if (typeof value === 'string') {
                        return value.toLowerCase();
                    }
                    else if (typeof value === 'number' || typeof value === 'boolean') {
                        return value.toString();
                    }
                    return '';
                });
                // For text filters, check if row values start with any of the selectedValues
                if (filterInfo.type === 'text') {
                    let textFilterMatched = false;
                    for (let property in row) {
                        if (row.hasOwnProperty(property)) {
                            let rowValue = row[property] != null ? String(row[property]).toLowerCase() : '';
                            if (selectedValues.some(filterValue => rowValue.startsWith(filterValue))) {
                                textFilterMatched = true;
                                break;
                            }
                        }
                    }
                    if (!textFilterMatched)
                        return false;
                }
                else if (filterInfo.type === 'multi-select') {
                    let rowValue = row[filterName] != null ? String(row[filterName]).toLowerCase() : '';
                    let includesUndefined = selectedValues.includes('undefined');
                    if (!selectedValues.includes(rowValue) && !(includesUndefined && rowValue === '')) {
                        return false;
                    }
                }
            }
            return true;
        });
    }
    async updateTableView() {
        if (this.serverSidePagination) {
            this.selectAll = false;
        }
        if (this.serverSidePagination && this.serverPageChangeHandler) {
            const { rows, total } = await this.serverPageChangeHandler({
                page: this.currentPage,
                pageSize: this.paginationPageSize,
            });
            rows.forEach((row, index) => {
                var _a;
                const rowId = row.sampleNumber || `row_${(this.currentPage - 1) * this.paginationPageSize + index}`;
                row.__rowId = rowId;
                row.__checkbox = {
                    disabled: false,
                    checked: ((_a = this.selectedRows) === null || _a === void 0 ? void 0 : _a.has(rowId)) || false,
                    size: 's',
                    indeterminate: false,
                    error: false,
                };
            });
            this.rowData = rows;
            this.matchingResultsCount = total;
            if (this.gridApi) {
                this.gridApi.setGridOption('rowData', rows);
                this.updateHeaderCheckboxState();
            }
            const paginationElement = this.host.shadowRoot.querySelector('ifx-pagination');
            if (paginationElement) {
                paginationElement.setAttribute('total', total.toString());
            }
        }
        else {
            let visibleRowData;
            if (this.pagination) {
                const startIndex = (this.currentPage - 1) * this.paginationPageSize;
                const endIndex = startIndex + this.paginationPageSize;
                visibleRowData = this.allRowData.slice(startIndex, endIndex);
            }
            else {
                visibleRowData = this.allRowData;
            }
            if (this.enableSelection) {
                visibleRowData.forEach(row => {
                    var _a, _b;
                    if (!row.__checkbox) {
                        row.__checkbox = {
                            disabled: false,
                            checked: ((_a = this.selectedRows) === null || _a === void 0 ? void 0 : _a.has(row.__rowId)) || false,
                            size: 's',
                            indeterminate: false,
                            error: false,
                        };
                    }
                    else {
                        row.__checkbox.checked = ((_b = this.selectedRows) === null || _b === void 0 ? void 0 : _b.has(row.__rowId)) || false;
                    }
                });
            }
            this.rowData = visibleRowData;
            this.matchingResultsCount = this.allRowData.length;
            if (this.gridApi) {
                this.gridApi.setGridOption('rowData', this.rowData);
            }
            this.updateHeaderCheckboxState();
        }
    }
    clearAllFilters() {
        this.currentFilters = {};
        this.allRowData = [...this.originalRowData];
    }
    async onBtShowLoading() {
        this.gridApi.showLoadingOverlay();
    }
    setPaginationItemsPerPage() {
        const newItemsPerPage = this.paginationItemsPerPage;
        if (newItemsPerPage) {
            this.internalItemsPerPage = this.paginationItemsPerPage;
            const itemsPerPageArray = JSON.parse(this.internalItemsPerPage);
            const selectedOption = itemsPerPageArray.find(option => option.selected);
            if (selectedOption) {
                this.paginationPageSize = Number(selectedOption.value);
            }
            else if (itemsPerPageArray.length > 0) {
                this.paginationPageSize = Number(itemsPerPageArray[0].value);
            }
        }
    }
    componentWillLoad() {
        this.setPaginationItemsPerPage();
        this.uniqueKey = `unique-${Math.floor(Math.random() * 1000000)}`;
        this.rowData = this.getRowData();
        this.colData = this.getColData();
        this.updateFilterOptions();
        this.gridOptions = {
            suppressCellFocus: true,
            rowHeight: this.rowHeight === 'default' ? 40 : 32,
            headerHeight: 40,
            components: {
                checkboxCellRenderer: CheckboxCellRenderer,
                checkboxHeaderRenderer: CheckboxHeaderRenderer,
                customLoadingOverlay: CustomLoadingOverlay,
                customNoRowsOverlay: CustomNoRowsOverlay,
            },
            defaultColDef: {
                resizable: true,
                autoHeight: true,
            },
            suppressDragLeaveHidesColumns: true,
            enableCellTextSelection: true,
            onFirstDataRendered: this.onFirstDataRendered.bind(this),
            columnDefs: this.colData,
            rowData: this.rowData,
            loadingOverlayComponent: CustomLoadingOverlay,
            noRowsOverlayComponent: CustomNoRowsOverlay,
            noRowsOverlayComponentParams: {
                noRowsMessageFunc: () => 'No rows found', //at: ' + new Date().toLocaleTimeString(),
            },
            icons: {
                sortAscending: '<ifx-icon icon="arrow-triangle-up-16"></ifx-icon>',
                sortDescending: '<ifx-icon icon="arrow-triangle-down-16"></ifx-icon>',
                sortUnSort: '<a class="unsort-icon-custom-color"><ifx-icon icon="arrow-triangle-vertikal-16"></ifx-icon></a>',
            },
            rowDragManaged: this.colData.some(col => col.dndSource === true) ? true : false,
            animateRows: this.colData.some(col => col.dndSource === true) ? true : false,
            navigateToNextCell: params => {
                return this.focusCellIfContainingButton(params.api, params.nextCellPosition);
            },
            tabToNextCell: params => {
                var _a;
                // Returning null is deprecated so we return false if the result is null (browser handles tab behavior).
                return (_a = this.focusCellIfContainingButton(params.api, params.nextCellPosition)) !== null && _a !== void 0 ? _a : false;
            },
        };
    }
    focusCellIfContainingButton(api, cellPosition) {
        var _a;
        if (!cellPosition) {
            return null;
        }
        if (cellPosition.column.getColDef().field === 'button') {
            const rowNode = api.getDisplayedRowAtIndex(cellPosition.rowIndex);
            if (!rowNode) {
                // Row not yet rendered due to virtualization.
                return null;
            }
            const cellRenderers = api.getCellRendererInstances({
                rowNodes: [rowNode],
                columns: [cellPosition.column],
            });
            if (cellRenderers.length > 0) {
                const renderedContent = (_a = cellRenderers[0]) === null || _a === void 0 ? void 0 : _a.getGui();
                if (renderedContent) {
                    const button = renderedContent.querySelector('ifx-button');
                    if (button) {
                        setTimeout(() => {
                            var _a;
                            // Just calling button.focus() will not work because the focus of <ifx-button> will not be
                            // forwared to its child <a>-element (containing the tabindex attribute) due to shadow root.
                            // We must therefore grab the <a>-element manually first and then call focus() on it.
                            const focusableChild = (_a = button.shadowRoot) === null || _a === void 0 ? void 0 : _a.querySelector('a[tabindex]');
                            focusableChild === null || focusableChild === void 0 ? void 0 : focusableChild.focus();
                        }, 0);
                    }
                }
            }
        }
        return cellPosition;
    }
    async componentDidLoad() {
        if (this.container) {
            if (!isNestedInIfxComponent(this.host)) {
                const framework = detectFramework();
                trackComponent('ifx-table', await framework);
            }
            this.gridApi = createGrid(this.container, this.gridOptions);
            if (this.gridApi) {
                this.gridApi.sizeColumnsToFit({
                    defaultMinWidth: 100,
                });
                this.gridApi.setGridOption('columnDefs', this.colData);
                this.gridApi.setGridOption('rowData', this.rowData);
                if (this.pagination) {
                    const paginationElement = this.host.shadowRoot.querySelector('ifx-pagination');
                    if (paginationElement) {
                        paginationElement.addEventListener('ifxPageChange', this.handlePageChange.bind(this));
                    }
                }
                const sidebarFilterElements = this.host.querySelectorAll('ifx-filter-type-group');
                // Add an event listener to each SetFilter component
                sidebarFilterElements.forEach(sidebarFilterElement => {
                    sidebarFilterElement.addEventListener('ifxSidebarFilterChange', this.handleSidebarFilterChange.bind(this));
                });
                const topbarFilterElements = this.host.querySelectorAll('ifx-filter-bar');
                // Add an event listener to each SetFilter component
                topbarFilterElements.forEach(topbarFilterElement => {
                    topbarFilterElement.addEventListener('ifxTopbarFilterChange', this.handleTopbarFilterChange.bind(this));
                });
            }
        }
        this.updateTableView();
    }
    componentWillUnmount() {
        if (this.pagination) {
            const paginationElement = this.host.shadowRoot.querySelector('ifx-pagination');
            if (paginationElement) {
                paginationElement.removeEventListener('ifxPageChange', this.handlePageChange.bind(this));
            }
        }
        const sidebarFilters = this.host.shadowRoot.querySelectorAll('ifx-filter-type-group');
        // Remove the event listener from each SetFilter component
        sidebarFilters.forEach(sidebarFilter => {
            sidebarFilter.removeEventListener('ifxSidebarFilterChange', this.handleSidebarFilterChange.bind(this));
        });
        const topbarFilters = this.host.shadowRoot.querySelectorAll('ifx-filter-type-group');
        // Remove the event listener from each SetFilter component
        topbarFilters.forEach(topbarFilter => {
            topbarFilter.removeEventListener('ifxTopbarFilterChange', this.handleTopbarFilterChange.bind(this));
        });
    }
    async handlePageChange(event) {
        if (!this.pagination) {
            return;
        }
        this.currentPage = event.detail.currentPage;
        if (this.serverSidePagination) {
            this.selectAll = false;
        }
        if (this.serverSidePagination && this.serverPageChangeHandler) {
            const { rows, total } = await this.serverPageChangeHandler({
                page: this.currentPage,
                pageSize: this.paginationPageSize,
            });
            rows.forEach((row, index) => {
                var _a;
                const rowId = row.sampleNumber || `row_${(this.currentPage - 1) * this.paginationPageSize + index}`;
                row.__rowId = rowId;
                row.__checkbox = {
                    disabled: false,
                    checked: ((_a = this.selectedRows) === null || _a === void 0 ? void 0 : _a.has(rowId)) || false,
                    size: 's',
                    indeterminate: false,
                    error: false,
                };
            });
            this.rowData = rows;
            this.matchingResultsCount = total;
            if (this.gridApi) {
                this.gridApi.setGridOption('rowData', this.rowData);
                this.updateHeaderCheckboxState();
            }
            const paginationElement = this.host.shadowRoot.querySelector('ifx-pagination');
            if (paginationElement) {
                paginationElement.setAttribute('total', total.toString());
            }
        }
        else {
            const startIndex = (this.currentPage - 1) * this.paginationPageSize;
            const endIndex = startIndex + this.paginationPageSize;
            const visibleRowData = this.allRowData.slice(startIndex, endIndex);
            if (this.enableSelection) {
                visibleRowData.forEach(row => {
                    var _a, _b;
                    if (!row.__checkbox) {
                        row.__checkbox = {
                            disabled: false,
                            checked: ((_a = this.selectedRows) === null || _a === void 0 ? void 0 : _a.has(row.__rowId)) || false,
                            size: 's',
                            indeterminate: false,
                            error: false,
                        };
                    }
                    else {
                        row.__checkbox.checked = ((_b = this.selectedRows) === null || _b === void 0 ? void 0 : _b.has(row.__rowId)) || false;
                    }
                });
            }
            this.rowData = visibleRowData;
            if (this.gridApi) {
                this.gridApi.setGridOption('rowData', visibleRowData);
                this.updateHeaderCheckboxState();
            }
        }
    }
    isJSONParseable(str) {
        try {
            JSON.parse(str);
            return true;
        }
        catch (e) {
            return false;
        }
    }
    getRowData() {
        let rows = [];
        if (this.rows === undefined || this.rows === null) {
            return rows;
        }
        if (this.isJSONParseable(this.rows)) {
            rows = [...JSON.parse(this.rows)];
        }
        else if (Array.isArray(this.rows) || typeof this.rows === 'object') {
            rows = [...this.rows];
        }
        else {
            console.error('Unexpected value for rows: ', this.rows);
        }
        rows.forEach((row, index) => {
            if (!row.__rowId) {
                row.__rowId = `row_${index}_${Date.now()}_${Math.random()}`;
            }
        });
        if (this.enableSelection) {
            rows.forEach(row => {
                var _a;
                row.__checkbox = {
                    disabled: false,
                    checked: ((_a = this.selectedRows) === null || _a === void 0 ? void 0 : _a.has(row.__rowId)) || false,
                    size: 's',
                    indeterminate: false,
                    error: false,
                };
            });
        }
        this.allRowData = rows;
        this.originalRowData = [...rows];
        this.matchingResultsCount = this.allRowData.length;
        return rows.slice(0, this.paginationPageSize);
    }
    updateCheckboxStates() {
        const dataToUpdate = this.rowData;
        dataToUpdate.forEach(row => {
            if (row.__checkbox) {
                row.__checkbox.checked = this.selectedRows.has(row.__rowId);
            }
        });
        if (this.gridApi) {
            this.gridApi.refreshCells({
                columns: ['__checkbox'],
                force: true,
            });
        }
    }
    emitSelectionChange() {
        const selectedRowsArray = Array.from(this.selectedRowsData.values());
        let isSelectAll;
        if (this.serverSidePagination) {
            const currentPageSelectedCount = this.rowData.filter(row => this.selectedRows.has(row.__rowId)).length;
            isSelectAll = currentPageSelectedCount === this.rowData.length && this.rowData.length > 0;
        }
        else {
            isSelectAll = this.selectedRows.size === this.allRowData.length && this.allRowData.length > 0;
        }
        this.host.dispatchEvent(new CustomEvent('ifxSelectionChange', {
            detail: {
                selectedRows: selectedRowsArray,
                selectedCount: selectedRowsArray.length,
                isSelectAll: isSelectAll,
            },
            bubbles: true,
        }));
    }
    getColData() {
        var _a, _b;
        let cols = [];
        if (this.cols === undefined || this.cols === null)
            return cols;
        if (this.isJSONParseable(this.cols)) {
            cols = [...JSON.parse(this.cols)];
        }
        else if (Array.isArray(this.cols) || typeof this.cols === 'object') {
            cols = [...this.cols];
        }
        else {
            console.error('Unexpected value for cols: ', this.cols);
        }
        if (this.enableSelection) {
            const checkboxColumn = {
                headerName: '',
                field: '__checkbox',
                width: 50,
                pinned: 'left',
                cellRenderer: 'checkboxCellRenderer',
                cellRendererParams: {
                    onCheckboxClick: (_a = this.handleRowCheckboxClick) === null || _a === void 0 ? void 0 : _a.bind(this),
                },
                headerComponent: 'checkboxHeaderRenderer',
                headerComponentParams: {
                    onSelectAll: (_b = this.handleSelectAll) === null || _b === void 0 ? void 0 : _b.bind(this),
                },
                sortable: false,
                filter: false,
                resizable: false,
                valueFormatter: undefined,
                cellDataType: false,
            };
            cols.unshift(checkboxColumn);
        }
        cols.forEach(column => {
            var _a, _b, _c, _d;
            const field = ((_a = column.field) === null || _a === void 0 ? void 0 : _a.toLowerCase()) || '';
            // --- Button columns ---
            if (field.startsWith('button')) {
                column.cellRenderer = ButtonCellRenderer;
                column.valueFormatter = undefined;
                column.cellDataType = false;
                if ((_b = this.buttonRendererOptions) === null || _b === void 0 ? void 0 : _b.onButtonClick) {
                    column.cellRendererParams = {
                        onButtonClick: this.buttonRendererOptions.onButtonClick,
                    };
                }
            }
            // --- Checkbox columns ---
            else if (field.startsWith('checkbox')) {
                column.cellRenderer = CheckboxCellRenderer;
                column.valueFormatter = undefined;
                column.cellDataType = false;
                if ((_c = this.checkboxRendererOptions) === null || _c === void 0 ? void 0 : _c.onCheckboxClick) {
                    column.cellRendererParams = {
                        onCheckboxClick: this.checkboxRendererOptions.onCheckboxClick,
                    };
                }
            }
            // --- Icon Button columns ---
            else if (field.startsWith('iconbutton') || field === 'iconButton') {
                column.cellRenderer = IconButtonCellRenderer;
                column.valueFormatter = undefined;
                column.cellDataType = false;
                if ((_d = this.iconButtonRendererOptions) === null || _d === void 0 ? void 0 : _d.onIconButtonClick) {
                    column.cellRendererParams = {
                        onIconButtonClick: this.iconButtonRendererOptions.onIconButtonClick,
                    };
                }
            }
            // --- Status columns ---
            else if (field.startsWith('status')) {
                column.cellRenderer = StatusCellRenderer;
                column.valueFormatter = undefined;
                column.cellDataType = false;
            }
            // --- Link columns ---
            else if (field.startsWith('link')) {
                column.cellRenderer = LinkCellRenderer;
                column.valueFormatter = undefined;
                column.cellDataType = false;
            }
        });
        return cols;
    }
    onFirstDataRendered(params) {
        params.api.sizeColumnsToFit();
    }
    handleResetButtonClick() {
        const resetEvent = new CustomEvent('ifxResetFiltersEvent', { bubbles: true, composed: true });
        window.dispatchEvent(resetEvent);
        this.clearAllFilters();
        this.updateTableView();
    }
    disconnectedCallback() {
        if (this.pagination) {
            const paginationElement = this.host.shadowRoot.querySelector('ifx-pagination');
            if (paginationElement) {
                paginationElement.removeEventListener('ifxPageChange', this.handlePageChange);
            }
        }
        const resetButton = this.host.shadowRoot.querySelector('#reset-filters-button');
        if (resetButton) {
            resetButton.removeEventListener('click', this.handleResetButtonClick.bind(this));
        }
    }
    getTableClassNames() {
        return classNames(this.tableHeight === 'auto' && 'table-wrapper ag-root-wrapper-body', 'table-wrapper');
    }
    render() {
        let style = {};
        if (this.tableHeight !== 'auto') {
            style = {
                height: this.tableHeight,
            };
        }
        const filterClass = this.filterOrientation === 'topbar' ? 'topbar-layout' : this.filterOrientation === 'none' ? '' : 'sidebar-layout';
        return (h(Host, { key: 'a0421844e9c61683bd742e73f1809ffe3e0e6bad' }, h("div", { key: 'cdbddf03c9ec9508afe475280031ac789465c924', class: "table-container" }, this.filterOrientation === 'sidebar' && (h("div", { key: '9190967ad17c4bc873461f9679857aecfc42cf29', class: "sidebar-btn" }, h("ifx-button", { key: 'e6af658a82fa88e87b3b2cc3d377268d4b8e2cf4', type: "button", disabled: false, variant: "secondary", size: "m", target: "_blank", theme: "default", "full-width": "false", onClick: () => this.toggleSidebarFilters() }, h("ifx-icon", { key: '20be3fda6b40d956202c70dd8f2d5b8e27fccca1', icon: "cross-16" }), this.showSidebarFilters ? 'Hide Filters' : 'Show Filters'))), h("div", { key: 'b886df2920915f2e26b9e92a29f95971c769fe0c', class: filterClass }, this.filterOrientation === 'sidebar' && this.showSidebarFilters && (h("div", { key: '768e749d6bb7294581916fa350ab6db406fd56cc', class: "sidebar-container" }, h("div", { key: '00e5ee6ae4127e25ed6f354431fb50826a5738b7', class: "filters-title-container" }, h("span", { key: 'c40714d09dae34e2fe4ca75f4ddb12f4c81b37da', class: "filters-title" }, "Filters")), h("div", { key: '4c182b7dd4fe8996011025af996c1a2c8815c6d2', class: "set-filter-wrapper-sidebar" }, (this.filterOrientation !== 'sidebar' || this.showSidebarFilters) && h("slot", { key: '8a7dc422f3e4382554eb2af47de00ed53442d1d5', name: "sidebar-filter" })))), this.filterOrientation !== 'none' && this.filterOrientation !== 'sidebar' && (h("div", { key: '0f1ee29a1bc041554cdc65108136c646efc7b934', class: "set-filter-wrapper-topbar" }, (this.filterOrientation !== 'sidebar' || this.showSidebarFilters) && h("slot", { key: 'c9ce08d1026ebfc80ddd3a11bbe1b26a09e58c64', name: "topbar-filter" }))), h("div", { key: '12f0b8bcb4dcebe0b57779f09ac703a76c741df0', class: "table-pagination-wrapper" }, this.filterOrientation !== 'none' && this.filterOrientation !== 'topbar' && this.showSidebarFilters && (h("div", { key: '50fae34e9d7652ad2d27a2dbe10a973cc559f61b', class: "filter-chips" }, Object.keys(this.currentFilters).map(name => {
            const filter = this.currentFilters[name];
            const filterValues = filter.filterValues;
            const isMultiSelect = filter.type !== 'text';
            return filterValues.length > 0 ? (h("ifx-chip", { placeholder: name, size: "large", variant: isMultiSelect ? 'multi' : 'single', readOnly: true, value: filterValues, key: name }, filterValues.map(filterValue => (h("ifx-chip-item", { value: filterValue, selected: true, key: filterValue }, filterValue))))) : null;
        }))), h("div", { key: 'a3d61c90ad5d8744be6c55d7790551a53d5388e9', class: "headline-wrapper" }, this.filterOrientation !== 'none' && this.headline && (h("div", { key: '598c04897a782b9f7fa8ea69b202e17c5db87142', class: "matching-results-container" }, h("span", { key: '174bbc64858c0b952eef4e289ec25a88f6a13ba5', class: "matching-results-count" }, "(", this.matchingResultsCount, ")"), h("span", { key: 'fa4e1a350a97794ba1c0390176d7413c19ff9286', class: "matching-results-text" }, this.headline))), h("div", { key: '52105af6541e2a5588dc0307c20d7e4b3e72220c', class: "inner-buttons-wrapper" }, h("slot", { key: 'fe68a9b64d3ed0fcbdb6a2ac9f2092fb9c921974', name: "inner-button" }))), h("div", { key: 'd3001b399da78d9e6005f4cf262a7f74b77b9cb4', id: "table-wrapper", class: this.getTableClassNames() }, h("div", { key: '4cc86621f42cb3c4de69618957297666e7df04a3', id: `ifxTable-${this.uniqueKey}`, class: `ifx-ag-grid ${this.variant === 'zebra' ? 'zebra' : ''}`, style: style, ref: el => (this.container = el) })), h("div", { key: 'ffea3142fecc04ca051aeeefd17dc9860ca8a1e1', class: "pagination-wrapper" }, this.pagination ? (h("ifx-pagination", { total: this.serverSidePagination ? this.matchingResultsCount : this.allRowData.length, "current-page": this.currentPage, "items-per-page": this.internalItemsPerPage })) : null))))));
    }
    hasButtonCol() {
        return this.getColData().some(column => column.field === 'button');
    }
    onDragOver(event) {
        var dragSupported = event.dataTransfer.length;
        if (dragSupported) {
            event.dataTransfer.dropEffect = 'move';
        }
        event.preventDefault();
    }
    onDrop(event) {
        var jsonData = event.dataTransfer.getData('application/json');
        var eJsonRow = document.createElement('div');
        eJsonRow.classList.add('json-row');
        eJsonRow.innerText = jsonData;
        var eJsonDisplay = document.querySelector('#eJsonDisplay');
        eJsonDisplay.appendChild(eJsonRow);
        event.preventDefault();
    }
    static get is() { return "ifx-table"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["table.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["table.css"]
        };
    }
    static get properties() {
        return {
            "cols": {
                "type": "any",
                "attribute": "cols",
                "mutable": false,
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "rows": {
                "type": "any",
                "attribute": "rows",
                "mutable": false,
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "buttonRendererOptions": {
                "type": "unknown",
                "attribute": "button-renderer-options",
                "mutable": false,
                "complexType": {
                    "original": "{ onButtonClick?: (params: any, event: Event) => void }",
                    "resolved": "{ onButtonClick?: (params: any, event: Event) => void; }",
                    "references": {
                        "Event": {
                            "location": "global",
                            "id": "global::Event"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "iconButtonRendererOptions": {
                "type": "unknown",
                "attribute": "icon-button-renderer-options",
                "mutable": false,
                "complexType": {
                    "original": "{ onIconButtonClick?: (params: any, event: Event) => void }",
                    "resolved": "{ onIconButtonClick?: (params: any, event: Event) => void; }",
                    "references": {
                        "Event": {
                            "location": "global",
                            "id": "global::Event"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "checkboxRendererOptions": {
                "type": "unknown",
                "attribute": "checkbox-renderer-options",
                "mutable": false,
                "complexType": {
                    "original": "{ onCheckboxClick?: (params: any, event: Event) => void }",
                    "resolved": "{ onCheckboxClick?: (params: any, event: Event) => void; }",
                    "references": {
                        "Event": {
                            "location": "global",
                            "id": "global::Event"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "rowHeight": {
                "type": "string",
                "attribute": "row-height",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "'default'"
            },
            "tableHeight": {
                "type": "string",
                "attribute": "table-height",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "'auto'"
            },
            "pagination": {
                "type": "boolean",
                "attribute": "pagination",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "true"
            },
            "paginationItemsPerPage": {
                "type": "string",
                "attribute": "pagination-items-per-page",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "filterOrientation": {
                "type": "string",
                "attribute": "filter-orientation",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "'sidebar'"
            },
            "headline": {
                "type": "string",
                "attribute": "headline",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "''"
            },
            "variant": {
                "type": "string",
                "attribute": "variant",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "'default'"
            },
            "serverSidePagination": {
                "type": "boolean",
                "attribute": "server-side-pagination",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "false"
            },
            "serverPageChangeHandler": {
                "type": "unknown",
                "attribute": "server-page-change-handler",
                "mutable": false,
                "complexType": {
                    "original": "(params: { page: number; pageSize: number }) => Promise<{ rows: any[]; total: number }>",
                    "resolved": "(params: { page: number; pageSize: number; }) => Promise<{ rows: any[]; total: number; }>",
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "enableSelection": {
                "type": "boolean",
                "attribute": "enable-selection",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "false"
            },
            "showLoading": {
                "type": "boolean",
                "attribute": "show-loading",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "false"
            }
        };
    }
    static get states() {
        return {
            "currentPage": {},
            "rowData": {},
            "colData": {},
            "filterOptions": {},
            "currentFilters": {},
            "uniqueKey": {},
            "paginationPageSize": {},
            "showSidebarFilters": {},
            "matchingResultsCount": {},
            "selectedRows": {},
            "selectAll": {},
            "selectedRowsData": {}
        };
    }
    static get methods() {
        return {
            "onBtShowLoading": {
                "complexType": {
                    "signature": "() => Promise<void>",
                    "parameters": [],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            }
        };
    }
    static get elementRef() { return "host"; }
    static get watchers() {
        return [{
                "propName": "rows",
                "methodName": "rowsChanged"
            }, {
                "propName": "cols",
                "methodName": "colsChanged"
            }, {
                "propName": "buttonRendererOptions",
                "methodName": "onButtonRendererOptionsChanged"
            }, {
                "propName": "iconButtonRendererOptions",
                "methodName": "onIconButtonRendererOptionsChanged"
            }, {
                "propName": "checkboxRendererOptions",
                "methodName": "onCheckboxRendererOptionsChanged"
            }];
    }
    static get listeners() {
        return [{
                "name": "ifxItemsPerPageChange",
                "method": "handleResultsPerPageChange",
                "target": undefined,
                "capture": false,
                "passive": false
            }, {
                "name": "ifxChange",
                "method": "handleChipChange",
                "target": undefined,
                "capture": false,
                "passive": false
            }];
    }
}
//# sourceMappingURL=table.js.map
