import { asyncDelay, onHomeworkFinish } from "../script/util";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent";
import pg from "./pg";
import Game from "./Game";
import {
    showFireworks,
} from '../script/utils';

const { ccclass, property } = cc._decorator;

@ccclass
export default class NewClass extends MyCocosSceneComponent {
    addPreloadImage() {
        this.log("test addPreloadImage")
        // TODO 根据自己的配置预加载图片资源
        this.data && this._imageResList.push({ url: this.data.pic_url });
        this.data && this._imageResList.push({ url: this.data.pic_url_2 });
    }

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

    addPreloadAnima() {
        this.log("test addPreloadAnima")

    }

    onLoadEnd() {
        this.log("test onLoadEnd")
        // TODO 加载完成后的逻辑写在这里, 下面的代码仅供参考
        this.initData();
        this.initView();
        this.initEvent();
    }
    protected onDestroy(): void {
        cc.Tween.stopAll();
        this.unscheduleAllCallbacks();
        pg.event.off("game_start")
        pg.event.off("item_touch_right")
        pg.event.off("speak_success");
        pg.event.off("speak_fail");
    }

    _cantouch = null;
    gameData = null;
    initData() {
        this.log("test initData")
        // 所有全局变量 默认都是null 
        this._cantouch = true;
        Game.getIns().init();
        //开始显示企鹅
    }
    initView() {
        this.log("test initView")
    }
    initEvent() {
        this.log("test initEvent")
        pg.event.on("game_start", () => { this.onGameStart() })

        pg.event.on("item_touch_right", (data) => { this.onTouchRight(data) })
        pg.event.on("speak_success", () => { this.onSpeakScueess() });
        pg.event.on("speak_fail", () => { this.onSpeakFail() });
    }
    //-----------------------------流程------------------------------
    onGameStart() {
        this.log("test onGameStart")
        Game.getIns().reset();
        this.scheduleOnce(() => {
            pg.event.emit("game_start_loop")
        }, 2)
    }
    private touchData: any;
    onTouchRight(data) {
        if (Game.getIns().isRobot) {
            this.onSpeakScueess();
        } else {
            this.touchData = data;
            pg.event.emit("speak_open", data.text);
        }
    }
    onSpeakScueess() {
        //执行后续的动作。
        this.touchData && this.touchData.cbSuccess && this.touchData.cbSuccess();
        Game.getIns().addScore()
        pg.event.emit("player_point_update");
        if (Game.getIns().isOver) {
            this.gameOver();
        }
    }
    onSpeakFail() {
        //回退到最后一个位置
        this.touchData && this.touchData.cbFailed && this.touchData.cbFailed();
    }
    //----------------------------小企鹅-------------------



    //----------------------------OVER-------------------
    gameOver() {
        let state = pg.view.find(this, "state");
        let bg_win = pg.view.find(state, "bg_win");
        let bg_lose = pg.view.find(state, "bg_lose");
        pg.view.visible(state, true);
        if (Game.getIns().playerScore > Game.getIns().robotScore) {
            pg.view.visible(bg_win, true);
            pg.view.visible(bg_lose, false);
            this.showFireFlower();
        } else {
            pg.view.visible(bg_win, false);
            pg.view.visible(bg_lose, true);
        }
        this.scheduleOnce(() => {
            pg.view.visible(bg_win, false);
            pg.view.visible(bg_lose, false);
            pg.event.emit("game_over");
        }, 5)
        // onHomeworkFinish最后需要添加作业完成
        onHomeworkFinish();
    }
    //-----------------------------TOOL-------------------------------
    showFireFlower() {
        return new Promise((resolve, reject) => {
            this.playLocalAudio("flower")
            showFireworks(
                this.node,
                pg.view.find(this, 'RibbonNodeBase').children,
                cc.v2(0, -600), cc.v2(0, 1000), 200, 200
            );
            showFireworks(
                this.node,
                pg.view.find(this, 'RibbonNodeBase').children,
                cc.v2(-600, -600), cc.v2(200, 1000), 200, 200
            );
            showFireworks(
                this.node,
                pg.view.find(this, 'RibbonNodeBase').children,
                cc.v2(600, -600), cc.v2(-200, 1000), 200, 200
            );
            setTimeout(() => {
                resolve('');
            }, 1500);
        });
    }
    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);
            });
        })
    }
}
