import { viewRegistry } from "../tabs/viewRegistry";

export default class ViewLoader {

    constructor({ tabManager, eventBus, api }) {

        this.tabManager = tabManager;
        this.eventBus = eventBus;
        this.api = api;

        // cache کلاس View ها
        this.cache = new Map();

        // registry مسیر view ها
        this.registry = viewRegistry;
    }


    async load(viewName, options = {}) {

        if (!this.registry[viewName]) {
            throw new Error(`View "${viewName}" is not registered`);
        }

        let ViewClass;

        // اگر قبلاً load شده
        if (this.cache.has(viewName)) {

            ViewClass = this.cache.get(viewName);

        } else {

            const module = await this.registry[viewName]();

            ViewClass = module.default || module;

            this.cache.set(viewName, ViewClass);

        }

        // باز کردن View در TabManager
        this.tabManager.openTab(ViewClass, {
            api: this.api,
            eventBus: this.eventBus,
            viewLoader: this, // برای Sidebar یا View های دیگر
            ...options
        });
    }

}
