import BaseView from "../../core/BaseView.js";
import { viewRegistry } from "../../core/registries.js";

import SchemaLoader from "../runtime/SchemaLoader.js";
import { Runtime } from "../runtime/runtime.js";

import "../runtime/register-components.js";
import "../runtime/runtime-bootstrap.js";

import ProjectsTable from "../runtime/table/ProjectsTable.js";
import ProjectsToolbar from "../runtime/toolbar/ProjectsToolbar.js";
import ProjectEditModal from "../runtime/modal/ProjectEditModal.js";
import ProjectsRuntimeEvents from "../runtime/runtime/ProjectsRuntimeEvents.js";

class ProjectsRuntimeView extends BaseView {

    static title = "لیست پروژه‌ها";

    // نمایش badge پروژه فعال در header
    useContextBadge = true;

    constructor(props = {}) {
        super(props);

        this.api = props.api;

        this.schemaLoader = new SchemaLoader(this.api);

        this.table = null;
        this.toolbar = null;
        this.modal = null;
        this.runtimeEvents = null;
    }

    async render(container) {
        await super.render(container);

        const body = this.ref("body");

        body.innerHTML = `
            <div class="projects-runtime-wrapper">
                <div class="projects-runtime-toolbar"></div>
                <div class="projects-runtime-table"></div>
            </div>
        `;

        const schema = await this.schemaLoader.load("projects");

        this.table = new ProjectsTable({
            api:      this.api,
            schema:   schema,
            store:    this.store,
            eventBus: this.eventBus,
        });

        this.toolbar = new ProjectsToolbar({
            table: this.table
        });

        this.modal = new ProjectEditModal({
            api: this.api,
            table: this.table,
            schema: schema,
            onSaved: async () => {
                await this.table.reload();
            }
        });


        this.runtimeEvents = new ProjectsRuntimeEvents({
            modal: this.modal
        });

        this.table.mount(
            body.querySelector(".projects-runtime-table")
        );

        this.toolbar.mount(
            body.querySelector(".projects-runtime-toolbar")
        );

        this.modal.mount(body);

        return this;
    }


    destroy() {
        dbg("Destroying ProjectsRuntimeView...");

        this.table?.destroy?.();
        this.toolbar?.destroy?.();
        this.modal?.destroy?.();

        if (this.runtimeEvents && typeof this.runtimeEvents.destroy === "function") {
            this.runtimeEvents.destroy();
        }

        super.destroy();
    }


}

// ثبت ویو در رجیستری
viewRegistry.register("projectsAuo", ProjectsRuntimeView);

export default ProjectsRuntimeView;
