import { SphereGeometry, Mesh, MeshStandardMaterial, Group } from "three";
import { EventManager } from '@/lib/EventManager';

class SceneSwitcher extends EventManager{
    emits = ['sceneSwitch']
    constructor(engine, data){
        super();
        return new Promise(async(resolve, reject)=>{
            this.source = this;
            if (data.switchType == 'award'){
                let gltf = await engine.load('trophy.glb', '/static/meshes/scene-switcher/');
                let awards = {};
                gltf.scene.traverse(o=>{
                    awards[o.name] = o;
                    o.position.multiplyScalar(0);
                })
                this.object = engine.meshUtils.wrapInGroup(awards.silver);
                this.object.addEventListener('io-activate', ()=>{
                    engine.motionQueue.add({ 
                        o: this.object,
                        a:{rotation: { y: k=>k*Math.PI*2 }}, r: true, t: 4 
                    })
                })
                this.object.addEventListener('io-deactivate', ()=>{
                    engine.motionQueue.clear(this.object, true)
                })
            }else if(data.switchType == 'sphere'){
                let geo = new SphereGeometry(1);
                let material = new MeshStandardMaterial({
                    map: await engine.loadTexture(data.$go_env.asset.name)
                })
                let sphere = new Mesh(geo, material);
                sphere.position.y = 0.5;
                this.object = engine.meshUtils.wrapInGroup(sphere);
                this.object.addEventListener('io-activate', ()=>{
                    engine.motionQueue.add({ 
                        o: sphere,
                        a:{ scale: (k,s)=>s.setScalar(1+0.05*Math.sin(4*k*Math.PI)) }, r: true, t: 4 
                    })
                })
                this.object.addEventListener('io-deactivate', ()=>{
                    engine.motionQueue.clear(sphere, true)
                })
            }else{
                //sensor, TODO!!!, to be implemented
            }
            engine.clickable.add(this.object, async e=>{
                this.dispatchEvent({type:'sceneSwitch', scene: data.switchScene});
            })
            resolve(this);
        })
    }
}

export { SceneSwitcher }