/**
 * @file MainApp.ts
 * @description 主应用类，负责初始化和协调所有子模块
 */

import { AppEngin } from './AppEngin';
import { AppScene } from './AppScene';
import { AppCamera } from './AppCamera';
import { AppLight } from './AppLight';
import { AppEnv } from './AppEnv';
import { AppModel } from './AppModel';
import { AppConfig } from './AppConfig';
import { AppRay } from './AppRay';
import { EventBridge } from '../event/bridge';

/**
 * 主应用类 - 3D场景的核心控制器
 * 负责管理DOM、引擎、场景、相机、灯光、环境、模型和动画等子模块
 */
export class MainApp {
    appEngin: AppEngin;
    appScene: AppScene;
    appCamera: AppCamera;
    appModel: AppModel;
    appLight: AppLight;
    appEnv: AppEnv;
    appRay: AppRay;


    constructor() {
        this.appEngin = new AppEngin(this);
        this.appScene = new AppScene(this);
        this.appCamera = new AppCamera(this);
        this.appModel = new AppModel(this);
        this.appLight = new AppLight(this);
        this.appEnv = new AppEnv(this);
        this.appRay = new AppRay(this);

        window.addEventListener("resize", () => this.appEngin.handleResize());
    }

    /**
     * 加载应用配置
     * @param config 配置对象
     */
    loadAConfig(config: any): void {
        AppConfig.container = config.container ;   
        AppConfig.modelUrlList = config.modelUrlList || [];
        AppConfig.env = config.env;
    }

    loadModel(): void {
        this.appModel.loadModel();
    }

    /** 唤醒/初始化所有子模块 */
    async Awake(): Promise<void> {
        this.appEngin.Awake();
        this.appScene.Awake();
        this.appCamera.Awake();
        this.appLight.Awake();
        this.appEnv.Awake();
        this.appRay.Awake()
        this.appModel.initManagers();
        this.update();
        EventBridge.sceneReady({ scene: this.appScene.object });
    }

    /** 启动渲染循环 */
    update(): void {
        if (!this.appEngin.object) return;
        this.appEngin.object.runRenderLoop(() => {
            this.appScene.object?.render();
            this.appCamera.update();
        });
    }

    /** 销毁应用，释放所有资源 */
    async dispose(): Promise<void> {
        this.appModel?.clean();
        this.appEnv?.clean();
    }
}
