import Scene from "../views/Scene";
import SceneCtrl from "../ctrls/SceneCtrl";
import AnswerScene from "./AnswerScene";
import PanelCtrl from "../ctrls/PanelCtrl";
import RulePanel from "../RulePanel";
import Net from "../Net";
import { setShareImg, clearShareImg } from "../utils";
import { MUtils } from "../MUtils";

export default class MainScene extends Scene {
    get skinKey() { return "MainScene" }
    public btnStart: eui.Button;
    public btnRule: eui.Button;
    public qrcode: eui.Group;
    public qrcodeImg: eui.Image;

    onSkinComplete() {
        super.onSkinComplete();
        this.btnStart.onTap(this, () => {
            MUtils.doClickBuried("2");
            SceneCtrl.instance.change(AnswerScene);
        });
        this.btnRule.onTap(this, () => {
            PanelCtrl.instance.show(RulePanel);
        });

        this.checkWXState();
        MUtils.doShowBuried("1");
    }

    private checkWXState() {
        this.btnStart.enabled = false;
        this.qrcode.visible = false;
        Net.sendGet(Net.Url.GetWXUserState, undefined, (res) => {
            let subscribe: string = res["data"]["subscribe"];
            if (subscribe == "0") {
                this.showQRCode();
            } else if (subscribe == "1") {
                this.startGame();
            } else {
                console.error("invalid code", subscribe);
            }
        });
    }

    private async showQRCode() {
        MUtils.doShowBuried("4");
        this.btnStart.enabled = false;
        await RES.loadGroup("main_scene");
        this.qrcode.visible = true;
        let texture = await RES.getResAsync("main_qrcode_img_png") as egret.Texture;
        let t = this.qrcodeImg.parent.localToGlobal(this.qrcodeImg.x, this.qrcodeImg.y);
        setShareImg(texture.toDataURL("image/png"), new egret.Rectangle(t.x, t.y, this.qrcodeImg.width * MUtils.fixAreaRatio, this.qrcodeImg.height * MUtils.fixAreaRatio), 150, true
        );
    }

    private startGame() {
        clearShareImg();
        this.btnStart.enabled = true;
        this.qrcode.visible = false;
    }
}