import Global, { PROP_TYPE } from "./Global";
import ResultLayer from "./ResultLayer";
import { Sdk } from "./Sdk/Sdk";
import { SdkToutiao } from "./Sdk/SdkToutiao";
import SoundManager from "./SoundManager";
import Userdata from "./Userdata";

const { ccclass, property } = cc._decorator;

@ccclass
export default class Game extends cc.Component {
    public static instance: Game;

    @property(cc.Node)
    bricksRootNode: cc.Node = null;

    @property(cc.Prefab)
    brickPrefab: cc.Prefab = null;

    @property(cc.Label)
    levelLabel: cc.Label = null;

    @property(cc.Label)
    timeLabel: cc.Label = null;

    @property(cc.Label)
    gemsLabel: cc.Label = null;

    @property(cc.Node)
    loadingNode: cc.Node = null;

    @property(cc.Sprite)
    progressBarSprite: cc.Sprite = null;

    @property([cc.Node])
    starNodes: cc.Node[] = [];

    @property(cc.Node)
    playgroundNode: cc.Node = null;

    private currLevelStar = 0;
    private timeCounter = 0;
    private isPaused = false;
    private isStartGame = false;
    private playground = null;

    onLoad() {
        Game.instance = this;
        this.playground = this.playgroundNode.getComponent('Playground');

        this.node.on('updateInfo', () => {
            this.updateGems();
        })
    }

    onEnable() {
        this.updateGems();
        this.resetGame();
        this.schedule(() => {
            if (!this.isPaused && this.isStartGame) {
                this.timeCounter++;
                this.updateTime();
            }
        }, 1);

        if (Sdk.isToutiao) {
            SdkToutiao.startRecord();
        }
    }

    updateGems() {
        if (this && this.gemsLabel) {
            this.gemsLabel.string = Userdata.Gem.toString();
        }
    }

    resetGame() {
        this.isPaused = false;
        this.isStartGame = false;
        this.timeCounter = 0;

        this.playground.resetButtonTip();

        this.updateTime();
        this.updateLevelNum();
    }

    //重新加载游戏
    reloadLevel() {
        this.loadingNode.active = true;
        this.resetGame();
        this.playground.loadLevel(Userdata.SelectLevel, () => {
            this.loadingNode.active = false;
        });

        if (Sdk.isToutiao) {
            SdkToutiao.stopRecord(() => {
                SdkToutiao.startRecord();
            });
        }
    }

    updateTime() {
        let min = Math.floor(this.timeCounter / 60);
        let sec = this.timeCounter % 60;

        this.timeLabel.string = (min < 10 ? ('0' + min) : min) + ':' + (sec < 10 ? ('0' + sec) : sec);

        let rate = Math.max(0.05, 1 - (this.timeCounter / Global.THREE_STARS_TOTAL_TIME));
        this.updateProgress(rate);

        if (this.timeCounter == Global.SHOW_PROP_TIP_TIME) {
            this.playground.showButtonTipActions();
        }
    }

    /**
     * 
     * @param percent 0-1
     */
    updateProgress(percent: number) {
        this.progressBarSprite.fillRange = percent;

        if (percent >= 0.666) {
            this.showStar(3);
        } else if (percent >= 0.333) {
            this.showStar(2);
        } else {
            this.showStar(1);
        }
    }

    updateLevelNum() {
        this.levelLabel.string = '关卡 ' + Userdata.SelectLevel;
    }

    get Stars() {
        return this.currLevelStar;
    }

    set IsPause(v: boolean) {
        this.isPaused = v;
    }

    set IsStartGame(v: boolean) {
        this.isStartGame = v;
    }

    private showStar(star: number) {
        this.currLevelStar = star;

        if (star >= 1) {
            this.starNodes[0].active = true;
        } else {
            this.starNodes[0].active = false;
        }

        if (star >= 2) {
            this.starNodes[1].active = true;
        } else {
            this.starNodes[1].active = false;
        }

        if (star >= 3) {
            this.starNodes[2].active = true;
        } else {
            this.starNodes[2].active = false;
        }
    }

    gameover() {
        this.showResultLayer(false);
    }

    showResultLayer(isWin: boolean, isSkip: boolean = false) {
        this.isPaused = true;
        this.loadingNode.active = true;
        if (Sdk.isToutiao) {
            SdkToutiao.stopRecord(() => {
                this.loadResult(isWin, isSkip);
            });
        } else {
            this.loadResult(isWin, isSkip);
        }
    }

    loadResult(isWin: boolean, isSkip: boolean = false) {
        cc.loader.loadRes("prefabs/ui/ResultLayer", (err, prefab) => {
            let _node = cc.instantiate(prefab);
            _node.name = "ResultLayer";

            this.loadingNode.active = false;
            _node.parent = this.node;

            let res = _node.getComponent(ResultLayer);
            res.show(isWin, isSkip);
        });
    }

    onClickPause() {
        SoundManager.playButton();
        this.loadingNode.active = true;

        if (Sdk.isToutiao) {
            SdkToutiao.pauseRecord();
        }

        cc.loader.loadRes("prefabs/ui/PauseLayer", (err, prefab) => {
            let _node = cc.instantiate(prefab);
            _node.name = "PauseLayer";

            this.IsPause = true;

            this.loadingNode.active = false;
            _node.parent = this.node;
        });
    }

    showShop() {
        // Sdk.ins.isPaymentReady(ready => {
        //     if (ready) {//payment ready
        //         let loading = cc.find('Canvas/Loading');
        //         if (loading) {
        //             loading.active = true;
        //             loading.zIndex = 999;
        //         }

        //         cc.loader.loadRes("prefabs/ui/ShopLayer", (err, prefab) => {
        //             let _node = cc.instantiate(prefab);
        //             _node.name = "Shop";

        //             loading.active = false;
        //             _node.parent = cc.find('Canvas');
        //             _node.active = true;
        //         });
        //     }
        // });
    }

    onClickPropShoot() {
        Global.debounceClicks(() => {
            SoundManager.playButton();

            if (Userdata.Gem >= Global.PROP_SHOOT_COST) {
                Userdata.addGem(-Global.PROP_SHOOT_COST);
                this.updateGems();
                this.playground.pickupProp(PROP_TYPE.SHOOT3);
                Userdata.saveUserdata();
            } else {
                Global.showTip('钻石不足');
                this.showShop();
            }
        }, 'Game-onClickPropShoot');
    }

    onClickPropTimes() {
        Global.debounceClicks(() => {
            SoundManager.playButton();

            if (Userdata.Gem >= Global.PROP_TIMES_COST) {
                Userdata.addGem(-Global.PROP_TIMES_COST);
                this.updateGems();
                this.playground.pickupProp(PROP_TYPE.TIMES3);
                Userdata.saveUserdata();
            } else {
                Global.showTip('钻石不足');
                this.showShop();
            }
        }, 'Game-onClickPropTimes');
    }

    onClickPropWall() {
        Global.debounceClicks(() => {
            SoundManager.playButton();

            if (Userdata.Gem >= Global.PROP_WALL_COST) {
                Userdata.addGem(-Global.PROP_WALL_COST);
                this.updateGems();
                this.playground.pickupProp(PROP_TYPE.WALL);
                Userdata.saveUserdata();
            } else {
                Global.showTip('钻石不足');
                this.showShop();
            }
        }, 'Game-onClickPropWall');
    }

    onClickWatchAds() {
        Global.debounceClicks(() => {
            SoundManager.playButton();
            let isGot = false;
            if (Sdk.isToutiao) {
                SdkToutiao.pauseRecord();
                SdkToutiao.showRewardVideoAd(() => {
                    this.showResultLayer(true, true);
                    Global.showTip('成功跳过关卡 !!');
                }, () => {
                    Global.showTip('广告展示失败,请稍后重试!');
                    SdkToutiao.resumeRecord();
                });
            } else {
                Sdk.ins.showVideoAd((res) => {
                    if (res) {
                        // Userdata.addGem(Global.WATCH_VIDEO_GEM);
                        // Global.showTip('Got ' + Global.WATCH_VIDEO_GEM + ' gems.');
                        // this.updateGems();
                        // Userdata.saveUserdata();
                        if (!isGot) {
                            isGot = true;
                            this.showResultLayer(true, true);
                            Global.showTip('成功跳过关卡 !!');
                            // Global.showTip('Level Skipped !!');
                        }
                    } else {
                        //Global.showTip('Ads not ready!');
                        Global.showTip('广告展示失败,请稍后重试!');
                    }
                });
            }
        }, 'Game-onClickWatchAds');
    }


}
