import { 
    PlaneGeometry, MeshBasicMaterial, SRGBColorSpace, 
    VideoTexture, DoubleSide, Mesh
} from 'three';

import { EventManager } from '@/lib/EventManager';
class VideoPlayer extends EventManager {
    emits = ['finish']
    constructor(engine, data){
        super();
        let vi, plane;
        return new Promise((resolve, reject)=>{
            vi = document.createElement('video');
            vi.src = engine.assetPath + data.$go.asset.name;
            vi.addEventListener('loadedmetadata', ()=>{
                this.aspect = vi.videoWidth / vi.videoHeight;
                let geometry = new PlaneGeometry( this.aspect, 1 );
                let map = new VideoTexture( vi );
                map.colorSpace = SRGBColorSpace;
                let material = new MeshBasicMaterial( {
                    color: 0xffffff,
                    map,
                    transparent: true,
                    opacity: 0.5,
                    side: DoubleSide
                } );
                plane = new Mesh( geometry, material );
                this.object = plane;
                engine.clickable.add(plane, ()=>{
                    if (vi.paused){
                        vi.play();
                    }else{
                        vi.pause();
                    }
                });

                vi.addEventListener('play', ()=>{
                    material.opacity = 1
                    if (data.playInHud && engine.dashboard?.active){
                        engine.dashboard.attach(plane, {
                            skipTransition: data.skipTransition
                        });
                    }
                })
                vi.addEventListener('pause', ()=>{
                    //material.opacity = 0.5;
                    if (data.playInHud){
                        engine.dashboard?.detach(plane, {
                            skipTransition: data.skipTransition
                        });
                    }
                })
                vi.addEventListener('ended', ()=>{
                    this.dispatchEvent({type:'finish'})
                })
                this.video = vi;
                
                resolve(this);
            })
        })
    }
}

export { VideoPlayer }