import { h, Host } from "@stencil/core";
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 { CustomNoRowsOverlay } from "./customNoRowsOverlay";
import { CustomLoadingOverlay } from "./customLoadingOverlay";
import classNames from "classnames";
export class Table {
    constructor() {
        this.columnDefs = [];
        this.rowData = [];
        this.rowHeight = 'default';
        this.tableHeight = 'auto';
        this.variant = 'default';
        this.gridInitialized = false;
    }
    componentWillLoad() {
        this.uniqueKey = `unique-${Math.floor(Math.random() * 1000000)}`;
        this.setColsAndRows(); //needed?
        this.setGridOptions();
    }
    setGridOptions() {
        this.gridOptions = {
            rowHeight: this.rowHeight === 'default' ? 40 : 32,
            headerHeight: 40,
            defaultColDef: {
                resizable: true,
                autoHeight: true,
            },
            suppressCellFocus: true,
            enableCellTextSelection: true,
            suppressDragLeaveHidesColumns: true,
            suppressRowHoverHighlight: true,
            onFirstDataRendered: this.onFirstDataRendered,
            columnDefs: this.columnDefs,
            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.columnDefs.some((col) => col.dndSource === true) ? true : false,
            animateRows: this.columnDefs.some((col) => col.dndSource === true) ? true : false,
        };
    }
    setColsAndRows() {
        if (typeof this.rows === 'string' && typeof this.cols === 'string') {
            try {
                if (this.cols) {
                    this.columnDefs = JSON.parse(this.cols);
                }
                if (this.rows) {
                    this.rowData = JSON.parse(this.rows);
                }
            }
            catch (err) {
                console.error('Failed to parse input:', err);
            }
        }
        else if ((Array.isArray(this.rows) || typeof this.rows === 'object') && (Array.isArray(this.cols) || typeof this.cols === 'object')) {
            this.columnDefs = this.cols;
            this.rowData = this.rows;
        }
        else {
            console.error('Unexpected value for cols and rows:', this.rows, this.cols);
        }
    }
    getRowData() {
        let rows = [];
        if (typeof this.rows === 'string') {
            try {
                if (this.rows) {
                    rows = JSON.parse(this.rows);
                }
            }
            catch (err) {
                console.error('Failed to parse input:', err);
            }
        }
        else if (Array.isArray(this.rows) || typeof this.rows === 'object') {
            rows = this.rows;
        }
        else {
            console.error('Unexpected value for rows: ', this.rows);
        }
        return rows;
    }
    getColData() {
        let cols = [];
        if (typeof this.cols === 'string') {
            try {
                if (this.cols) {
                    cols = JSON.parse(this.cols);
                }
            }
            catch (err) {
                console.error('Failed to parse input:', err);
            }
        }
        else if (Array.isArray(this.cols) || typeof this.cols === 'object') {
            cols = this.cols;
        }
        else {
            console.error('Unexpected value for cols: ', this.cols);
        }
        return cols;
    }
    onFirstDataRendered(params) {
        params.api.sizeColumnsToFit();
    }
    componentWillUpdate() {
        this.setColsAndRows();
        this.gridOptions.columnDefs = this.columnDefs;
        this.gridOptions.rowData = this.rowData;
        if (this.gridApi) {
            this.gridApi.setGridOption('rowData', this.rowData);
            this.gridApi.setGridOption('columnDefs', this.columnDefs);
        }
    }
    async componentDidLoad() {
        if (this.container && !this.gridInitialized) {
            if (!isNestedInIfxComponent(this.host)) {
                const framework = detectFramework();
                trackComponent('ifx-basic-table', await framework);
            }
            this.gridApi = createGrid(this.container, this.gridOptions);
            if (this.gridApi) {
                this.gridApi.sizeColumnsToFit({
                    defaultMinWidth: 100,
                });
                this.gridApi.setGridOption('columnDefs', this.getColData());
                this.gridApi.setGridOption('rowData', this.getRowData());
                this.gridInitialized = true;
            }
        }
    }
    getClassNames() {
        return classNames(this.tableHeight === 'auto' && 'table-wrapper ag-root-wrapper-body', 'table-wrapper');
    }
    getTableStyle() {
        if (this.tableHeight !== 'auto') {
            return {
                height: this.tableHeight,
            };
        }
        return {};
    }
    render() {
        return (h(Host, { key: '16e707fb0fbd5e17a0731bb8b893ac0e52dd7d33' }, h("div", { key: '8e8b363ebd7f9eebbb6783b9e8306a91a746e911', id: "table-wrapper", class: this.getClassNames() }, h("div", { key: '32c531daad173f120369475c95fa1cdd6044a078', id: `ifxTable-${this.uniqueKey}`, class: `ifx-ag-grid ${this.variant === 'zebra' ? 'zebra' : ""}`, style: this.getTableStyle(), ref: (el) => (this.container = el) }))));
    }
    static get is() { return "ifx-basic-table"; }
    static get originalStyleUrls() {
        return {
            "$": ["table.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["table.css"]
        };
    }
    static get properties() {
        return {
            "cols": {
                "type": "string",
                "attribute": "cols",
                "mutable": false,
                "complexType": {
                    "original": "any[] | string",
                    "resolved": "any[] | string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "rows": {
                "type": "string",
                "attribute": "rows",
                "mutable": false,
                "complexType": {
                    "original": "any[] | string",
                    "resolved": "any[] | string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": 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'"
            },
            "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'"
            }
        };
    }
    static get states() {
        return {
            "gridOptions": {},
            "columnDefs": {},
            "rowData": {},
            "uniqueKey": {}
        };
    }
    static get elementRef() { return "host"; }
}
//# sourceMappingURL=table.js.map
