import { asyncDelay, onHomeworkFinish } from "../script/util_ns16_mole";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent_ns16_mole";
import Game, { GAME_STATE } from "./tool/GameNS16_ns16_mole";
import pg from "./tool/pg_ns16_mole";

const { ccclass, property } = cc._decorator;

@ccclass
export default class SceneComponent extends MyCocosSceneComponent {

    addPreloadImage() {
        // TODO 根据自己的配置预加载图片资源
        this._imageResList.push({ url: this.data.pic_url });
        this._imageResList.push({ url: this.data.pic_url_2 });
    }

    addPreloadAudio() {
        // TODO 根据自己的配置预加载音频资源
        this._audioResList.push({ url: this.data.audio_url });
    }

    addPreloadAnima() {

    }

    onLoadEnd() {
        // TODO 加载完成后的逻辑写在这里, 下面的代码仅供参考
        this.initData();
        this.initView();
        this.initEvent();
        this.log("statr!!!!!!!!!!!!!")
    }
    protected onDestroy(): void {
        pg.event.clear();
    }

    _cantouch = null;
    initData() {
        Game.getIns().init(this.data);
        Game.getIns().reset();
        // 所有全局变量 默认都是null 
        this._cantouch = true;
    }
    private layout_start: cc.Node;
    private audioId: any;
    async initView() {
        this.layout_start = pg.view.find(this, "layout_start");
        let desc = pg.view.find(this.layout_start, 'desc');
        pg.view.setString(desc, Game.getIns().question.text)

        this.layout_start.active = true;
        this.audioId = await pg.audio.playAudioByUrl(Game.getIns().question.audio);
        if (this.audioId > -1 && Game.getIns().state == GAME_STATE.RUNNING) {
            cc.audioEngine.stopAllEffects();
        }
    }
    initEvent() {
        pg.view.touchOn(pg.view.find(this.layout_start, 'btn_start'), this.onTouchStart, this);

        pg.event.on("game_start", () => {
            this.gameStart();
        })
        pg.event.on("game_time_over", () => {
            //这里的事件会发送的很早。但是我们需要等待动画执行完了之后再开始后续的内容
            Game.getIns().addPage();
            if (!Game.getIns().isOver) {
                let time = 1000;
                this.log("time: " + time)
                setTimeout(() => {
                    return pg.event.emit("show_round_action");
                }, time);
                return;
            }
            this.showGameOver();
        })
    }
    onTouchStart() {
        this.layout_start.active = false;
        if (this.audioId > -1) {
            cc.audioEngine.stopAllEffects();
        }
        this.playLocalAudio('btn');
        if (!Game.getIns().singleGame) {
            this.showVs();
        } else {
            pg.event.emit("show_round_action");
        }
    }

    gameStart() {
        //游戏开始小鱼出现等等
        this.layout_start.active = false;
        if (this.audioId > -1 && Game.getIns().state != GAME_STATE.WAIT) {
            cc.audioEngine.stopAllEffects();
        }
    }
    private showVs() {
        let vs = cc.find("vs", this.node);
        vs.active = true;
        let player1 = cc.find("player1", vs);
        let player2 = cc.find("player2", vs);
        let icon_vs = cc.find("icon_vs", vs);

        cc.tween(player1).delay(0.4).call(() => {
            this.playLocalAudio("move");
        }).to(0.5, { x: -270 }).start();
        cc.tween(player2).delay(0.4).to(0.5, { x: 270 }).start();
        cc.tween(icon_vs).delay(0.8).call(() => {
            this.playLocalAudio("vs");
            icon_vs.active = true;
        }).to(0.3, { scale: 1 })
            .delay(2)
            .call(() => { pg.event.emit("show_round_action"); vs.active = false; }).start();
    }
    private showGameOver() {
        let stoneP = Math.round(10 * Game.getIns().player.score / Game.getIns().total);
        let stoneR = 10 - stoneP;
        let player = {
            right: Game.getIns().player.score,
            error: Game.getIns().player.error,
            stone: stoneP
        }
        let robot = {
            right: Game.getIns().robot.score,
            error: Game.getIns().robot.error,
            stone: stoneR
        }
        let totalNumber = Game.getIns().totalNumber;
        if (Game.getIns().singleGame) {
            this.log("player: " + JSON.stringify({ player, totalNumber }));
            onHomeworkFinish({ player, totalNumber })
        } else {
            this.log("player: " + JSON.stringify({ player, robot, totalNumber }));
            onHomeworkFinish({ player, robot, totalNumber })
        }
        this.log("player: " + JSON.stringify(player));
        this.log("totalNumber: " + totalNumber)
    }

    playLocalAudio(audioName) {
        const audio = cc.find(`Canvas/res/audio/${audioName}`).getComponent(cc.AudioSource);
        return new Promise((resolve, reject) => {
            const id = cc.audioEngine.playEffect(audio.clip, false);
            cc.audioEngine.setFinishCallback(id, () => { resolve(id); });
        })
    }
}



