import { EventManager } from "@/lib/EventManager";
import { MeshStandardMaterial, MeshBasicMaterial, PlaneGeometry, Mesh, DoubleSide, FrontSide } from "three";

class ImageObject extends EventManager{
    emits = ['finish', 'interaction']
    constructor(engine, obj) {
        super();
        return new Promise(async(resolve, reject)=>{
            if (obj.$go){
                obj.path = engine.assetPath;
                obj.value = obj.$go.asset.name;
            }
            let t = await engine.loadTexture(obj.value, obj.path);
            let k = t.image.width / t.image.height;
            let mp = {
                map: t,
                alphaTest: 0.5,
                side: obj.singleSide? FrontSide : DoubleSide
            };
            if (obj.nm) {
                mp.normalMap = engine.loadTexture(obj.nm, obj.path);
            }
            if (obj.em) {
                mp.emissiveMap = engine.loadTexture(obj.em, obj.path);
            }
            if (obj.am) {
                mp.alphaMap = engine.loadTexture(obj.am, obj.path);
            }
            obj.material && Object.assign(mp, obj.material);
            let geo = new PlaneGeometry(obj.width || k, obj.height || 1);
            if (obj.uv) {
                var uvAttribute = geo.attributes.uv;
                for (var i = 0; i < uvAttribute.count; i++) {
                    uvAttribute.setXY(i, obj.uv[2 * i], obj.uv[2 * i + 1]);
                }
            }
            this.object = new Mesh(geo, mp.metalness ? new MeshStandardMaterial(mp) : new MeshBasicMaterial(mp));

            if (obj.description) {
                engine.clickable.add(this.object, ()=>{
                    this.dispatchEvent({type:'interaction'})
                    engine.dashboard.updateText(obj.description, {
                        hideOnFinish: true,
                        textScrolledCallback: ()=>{ this.dispatchEvent({type:'finish'}); }
                    })
                })
            }else{
                this.maxPoints = 0
            }

            resolve(this)
        })
    }
}

export {ImageObject}