import { THREE } from "threebox-plugin";
import FlyLine from "./flyLine";
import Particles from "./particles";

export default class ThreeJsLayer {
    constructor(map, renderTarget) {
        this.map = map;
        this.canvas = renderTarget;

        this.id = "threeJsLayer";
        this.type = "custom";
        this.renderingMode = "3d";
        this.flyLineList = [];
        this.destroyed = false;
    }

    onAdd(map, gl) {
        this.renderer = new THREE.WebGLRenderer({
            canvas: this.canvas,
            context: gl,
        });
        this.renderer.autoClear = false;
        this.camera = new THREE.Camera();
        this.scene = new THREE.Scene();
        this.particles = new Particles(this.scene);
    }

    // 使用粒子点亮一个区域
    lightupCoord(options) {
        if (!this.particles) return;
        this.particles.lightupCoord(options);
    }

    // 添加飞线
    addFlyLine(options) {
        this.flyLineList.push(new FlyLine(options, this.scene));
    }

    // 飞线动画
    animateFlyLine() {
        this.flyLineList.forEach((l) => l.animate());
    }

    // 粒子缩放
    scaleParticles() {
        if (!this.particles) return;
        const zoom = this.map.getZoom();
        this.particles.scale(zoom);
    }

    // 漂浮物
    setFlotsam(options) {
        if (!this.particles) return;
        this.particles.setFlotsam(options);
    }

    render(gl, matrix) {
        if (this.map.destroyed) return;
        const m = new THREE.Matrix4().fromArray(matrix);
        this.camera.projectionMatrix = m;
        this.renderer.resetState();
        this.renderer.render(this.scene, this.camera);

        this.animateFlyLine();
        this.scaleParticles();

        this.map.triggerRepaint();
    }

    destroy() {
        this.scene.children.forEach((m) => {
            if (m.geometry) m.geometry.dispose();
            if (m.material) m.material.dispose();
        });
        this.scene.children.forEach((m) => this.scene.remove(m));
        this.scene.remove(this.camera);
    }
}
