import { getBoundingBox, getBoundingBoxCenterPoint, getBoundingBoxMaxLength, centerOrigin } from "@/lib/MeshUtils";
import { EventManager } from '@/lib/EventManager';

class GenericObject extends EventManager{
    emits = ['finish']
    constructor(engine, data){
        super();
        return new Promise(async(resolve, reject)=>{
            this.source = await engine.load(data.$go.asset.name);
            this.object = centerOrigin(this.source.scene)

            if (!data.exclude){
                engine.clickable.add(this.object, async e=>{
                    this.object.__onhud = !this.object.__onhud;
                    if (engine.dashboard){
                        if (data.hud){
                            if (this.object._hud ){
                                engine.dashboard.detach(this.object);
                            }else{
                                let bb = getBoundingBox(this.object);
                                let scale = 0.5/getBoundingBoxMaxLength(bb);
                                let position = getBoundingBoxCenterPoint(bb, this.object.position).multiplyScalar(scale).negate()
                                
                                let placement = {
                                    quaternion: { x:0, y:0, z:0, w:0 },
                                    position,
                                    scale: { 
                                        x: scale*this.object.scale.x, 
                                        y: scale*this.object.scale.y, 
                                        z: scale*this.object.scale.z
                                    }
                                }
                                await engine.dashboard.attach(this.object, {
                                    placement, rotate: true, plane: true
                                });
                            }
                        }
                        if (data.description){
                            engine.dashboard.updateText(this.object.__onhud ? data.description : '', (d)=>{
                                d && this.dispatchEvent({type:'finish'})
                            })
                        }
                    }
                });
            }

            resolve(this);
        })
    }
}

export {GenericObject}