import {CustomElement, defineElement, Host, prop, state} from "../../packages/csx";
import TableComponentStyle from "./table-component.scss";

let tableId = 0;

@defineElement("tripto-table")
export class TableComponent extends CustomElement {

    #columnDefinitions;

    @prop()
    set columns(value) {
        this.#columnDefinitions = value;
    }

    @state() data;

    @prop()
    set data(value) {
        this.data = value;
    }

    #tableId = tableId++;
    render() {
        console.log(`Table render at for ${this.data?.length??0} rows: ${Date.now()}`);
        return (
            <Host>
                <style>{TableComponentStyle}</style>
                <style>
                    {this.#columnDefinitions?.map((col, idx) => (
                        `#table_${this.#tableId} .cell.cell_${idx} {` +
                        `   flex: ${(col.size ? (`0 0 ${col.size}px`) : `1`)};` +
                        `}`
                    ))}
                </style>
                <section className="table" id={`table_${this.#tableId}`}>
                    <header>
                        <div className="row">
                            {this.#columnDefinitions.map((col, idx) => (
                                <div className={`cell cell_${idx}`}>
                                    {col.headerRender()}
                                </div>
                            ))}
                        </div>
                    </header>
                    <main>
                        {this.data?.map(dataRow => (
                            <div className="row">
                                {this.#columnDefinitions.map((col, idx) => (
                                    <div className={`cell cell_${idx}`}>
                                        {col.render(dataRow)}
                                    </div>
                                ))}
                            </div>
                        ))}
                    </main>
                </section>
            </Host>
        );
    }
}