import { Group, Color } from 'three';
import { EventManager } from '@/lib/EventManager';
import { TextObject } from '../TextObject/TextObject';
import Utils from '#/app/Utils';

class SingleQuestion extends EventManager {
    emits = ['finish', 'interaction']
    constructor(engine, data) {
        super();
        return new Promise(async (resolve, reject)=>{
            const container = new Group(); 
            const question = await new TextObject(engine, { text: data.q, fontSize: 0.125 });
            const answers = new Group();
            let ca = data.a[0];
            let ans = Utils.shuffleArray(data.a.filter(e=>!!e));
            for (let i=0; i<ans.length; i++){
                let a = ans[i];
                let qa = await new TextObject(engine, { text: `${i+1}). ${a}`, fontSize: 0.1 });
                qa.object.position.y = -0.15 * (i + 1);
                answers.add(qa.object);
                qa.object._answer = a;
                engine.clickable.add(qa.object, () => {
                    //if (!container.visible) return;
                    this.dispatchEvent({type:'interaction'});
                    engine.tm?.post('answer', i, {answer: a, correct: a == ca});
                    if (qa.object._answer == ca) {
                        this.dispatchEvent({type:'finish'})
                        qa.object.outlineColor = new Color(0x55ff55);
                        answers.children.forEach(c => engine.clickable.remove(c));
                    } else {
                        qa.object.outlineColor = new Color(0xff5555);
                        setTimeout(() => {
                            qa.object.outlineColor = new Color(0xffffff);
                        }, 1000);
                    }
                });
            }
            container.add(question.object);
            container.add(answers);
            this.object = engine.meshUtils.centerOrigin(container);
            resolve(this);
        })
    }
}

export { SingleQuestion }