import { GameState } from "./utils";

export class SubjectManager {
    private  _curSubJect = 0;//当前第几题
    private  _loactionCache;//所有题目
    private _curTmpSubject;//当前题目数据

    init(){
        
        this.insideAddEventListener();
    }
    private insideAddEventListener(){
        //初始化题目数据
        engine.globalEvent.addEventListener('handleOption',this.handleSubject,this)
        //更新题目
        engine.globalEvent.addEventListener('updateSubject',this.updateSubject,this)

        engine.globalEvent.addEventListener('handleResult',this.handleResult,this)

        engine.globalEvent.addEventListener('sendAnswerResult',this.sendAnswerResult,this)

        
    }

    private handleSubject(subject){
        this._curSubJect = 0;
        this._loactionCache = subject.data;
        this.updateSubject();
        engine.globalEvent.dispatchEvent('updateAnswerCount',{count:0})
    }

    private updateSubject(){
        if(this._curSubJect >= this._loactionCache.length){
            console.log('没有题目');
            engine.globalEvent.dispatchEvent('answer-game-over');
            return;
        }
        this._curTmpSubject = this._loactionCache[this._curSubJect];
        let title = this._loactionCache[this._curSubJect].question;
        let options = this._loactionCache[this._curSubJect].options;
        let tmpIndex = this._loactionCache[this._curSubJect].index;
        this.updateTitle(title,tmpIndex)
        this.updateOption(options);
        this._curSubJect++;
    }
    //更新题目
    private updateTitle(title,tmpIndex){
        engine.globalEvent.dispatchEvent('updateSubjectTitle',{title:title,curSubJect:tmpIndex});   
    }
    //更新选项
    private updateOption(options){
        engine.globalEvent.dispatchEvent('updateOption',{options:options});   
    }
    
    //处理正确答案及其答对的题数
    private handleResult(result){
        let tmp = result.data.result;
        //更新答对题数值
        engine.globalEvent.dispatchEvent('updateAnswerCount',{count:tmp.count})
        //更新答题结果
        engine.globalEvent.dispatchEvent('handleAnswerOption',{state:tmp.state})
    }
    //发送用户选择的答案
    sendAnswerResult(resultData){
        let tmpAnswer = resultData.data.answer;
        engine.globalEvent.dispatchEvent('answer-game-select',{curSubJect:this._curTmpSubject.index,answer:tmpAnswer});
    }

}