import { CubeTexture } from '@babylonjs/core/Materials/Textures/cubeTexture';
import { Monobehiver } from '../base/Monobehiver';
import { AppConfig } from './AppConfig';

/**
 * 环境管理类- 负责创建和管理HDR环境贴图
 */
export class AppEnv extends Monobehiver {
    object: CubeTexture | null;

    constructor(mainApp: any) {
        super(mainApp);
        this.object = null;
    }

    /** 初始化 - 创建默认HDR环境 */
    Awake(): void {
        this.createHDR();
    }

    /**
     * 创建HDR环境贴图
     * @param hdrPath HDR文件路径
     */
    createHDR(): void {
        const envPath = AppConfig.env.envPath;
        const intensity = AppConfig.env.intensity ?? 1.5;
        const rotationY = AppConfig.env.rotationY ?? 0;
        const scene = this.mainApp.appScene.object;
        if (!scene) return;
        if (this.object) {
            this.object.dispose();
            this.object = null;
        }
        const reflectionTexture = CubeTexture.CreateFromPrefilteredData(envPath, scene);
        reflectionTexture.rotationY = rotationY;
        scene.environmentIntensity = intensity;
        scene.environmentTexture = reflectionTexture;
        this.object = reflectionTexture;
    }

    /**
     * 修改HDR环境光强度
     * @param intensity 强度值
     */
    changeHDRIntensity(intensity: number): void {
        if (this.mainApp.appScene.object) {
            this.mainApp.appScene.object.environmentIntensity = intensity;
        }
    }

    /**
     * 旋转HDR环境贴图
     * @param angle 旋转角度(弧度)
     */
    rotateHDR(angle: number): void {
        if (this.object) this.object.rotationY = angle;
    }

    /** 清理资源 */
    clean(): void {
        if (this.object) {
            this.object.dispose();
            this.object = null;
        }
    }
}
