// CardGrid.js

import { Runtime } from './runtime.js';

export class CardGrid {

    constructor(config) {

        this.el = config.el;

        this.endpoint = config.endpoint;

        this.renderer = config.renderer;

        this.rows = {};

        this.init();

        this.bindEvents();
    }

    init() {

        this.table = new Tabulator(this.el, {

            ajaxURL: this.endpoint,

            layout: "fitColumns",

            pagination: true,

            paginationSize: 12,

            movableColumns: false,

            responsiveLayout: "collapse",

            rowFormatter: (row) => {

                const data = row.getData();

                this.rows[data.id] = row;
            },

            columns: [
                {
                    title: "Records",

                    field: "card",

                    formatter: (cell) => {

                        const data =
                            cell.getRow().getData();

                        return this.renderer(data);
                    }
                }
            ]
        });
    }

    bindEvents() {

        Runtime.bus.on('project-updated', () => {

            this.refresh();
        });

        Runtime.bus.on(
            'project-progress-changed',
            ({ id, progress }) => {

                const row = this.rows[id];

                if (!row) return;

                row.update({
                    progress
                });
            }
        );

        Runtime.bus.on(
            'project-data-changed',
            ({ id, updates }) => {

                const row = this.rows[id];

                if (!row) return;

                row.update(updates);
            }
        );

        Runtime.bus.on(
            'project-archived',
            ({ id }) => {

                const row = this.rows[id];

                if (!row) return;

                row.delete();

                delete this.rows[id];
            }
        );
    }

    refresh() {

        this.rows = {};

        this.table.replaceData();
    }

    getRow(id) {

        return this.rows[id] || null;
    }

    updateRow(id, updates) {

        const row = this.rows[id];

        if (!row) return;

        row.update(updates);
    }

    deleteRow(id) {

        const row = this.rows[id];

        if (!row) return;

        row.delete();

        delete this.rows[id];
    }

    addRow(data) {

        this.table.addData([data], true);
    }
}
