import Global from "./Global";
import Userdata from "./Userdata";
import SoundManager from "./SoundManager";
import { Sdk } from "./Sdk/Sdk";
import { SdkToutiao } from "./Sdk/SdkToutiao";
import Game from "./Game";

const { ccclass, property } = cc._decorator;

@ccclass
export default class RewardLayer extends cc.Component {
    // @property(cc.Label)
    // buttonNameLabel: cc.Label = null;

    isAds: boolean = false;
    isGot: boolean = false;
    eventNode: cc.Node = null;

    onClickClose() {
        Global.debounceClicks(() => {
            SoundManager.playButton();
            this.cliamReward(1);
            this.hide();
        }, 'RewardLayer-onClickClose');
    }

    hide() {
        this.node.destroy();
    }

    onDisable() {
        Userdata.saveUserdata();
    }

    setEventNode(node: cc.Node) {
        this.eventNode = node;
    }

    cliamReward(times: number) {
        Userdata.addGem(Global.SCORE_REWARD_GEM * times);
        Global.showTip("获得 " + (Global.SCORE_REWARD_GEM * times) + " 钻石.");

        let _node = cc.find('Canvas');
        if (_node && cc.isValid(_node)) {
            _node.emit('updateInfo');
        }
        // Game.instance.updateGems();
        if (this.eventNode && cc.isValid(this.eventNode)) {
            this.eventNode.emit('updateInfo');
        }
    }

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

            if (this.isGot) {
                return;
            }

            if (Sdk.isToutiao) {
                SdkToutiao.showRewardVideoAd(() => {
                    if (!this.isGot) {
                        this.isGot = true;
                        this.cliamReward(5);
                        this.hide();
                    }
                }, () => {
                    Global.showTip('广告展示失败, 请稍后重试!!');
                });
            } else {
                Sdk.ins.showVideoAd((res) => {
                    if (res) {
                        if (!this.isGot) {
                            this.isGot = true;
                            this.cliamReward(5);
                            this.hide();
                        }
                    } else {
                        Global.showTip('广告展示失败, 请稍后重试!!');
                        // Global.showTip('No ads ready!!');
                    }
                });
            }

        }, 'RewardLayer-onClickCliam');
    }
}
