import { sendWebNet, WebNetName } from "./Utils/WebNet/WebNet";
import {  hideWaiting, showWaiting } from "db://assets/Module/UIFast";
import { AESDecrypt, AESEncrypt } from "./Utils/Crypto";
import store from "./store/store";

export default class GameMgr {

    private static _ins: GameMgr = null;

    public static get ins() {
        !GameMgr._ins && (GameMgr._ins = new GameMgr());
        return GameMgr._ins;
    }

    gameInfo: {
        recordId: number,
    } = {
        recordId: 0,
    };

    /**
     * 开始游戏
     */
    async start() {
        showWaiting();
        const { success, data, code } = await sendWebNet(WebNetName.start, {
            entryTokenId: store.miniAppQuery.entryTokenId,
        }, { hideMsg: true });
        hideWaiting();

        store.updateIndex();
        if (!success) {
            return false;
        }

        const decrypt = JSON.parse(AESDecrypt(data, "FDF817451A60EB6F", "cDOiBC1n2QrkAY2P"));

        const { recordId } = decrypt;

        this.gameInfo = {
            recordId,
        }

        return true;
    }

    /**
     * 提交游戏结果
     */
    async submit(score: number) {

        showWaiting();

        const params = {
            recordId: this.gameInfo.recordId,
            score: score,
            level: 1,
            timestamp: Date.now(),
        }

        const encrypt = AESEncrypt(JSON.stringify(params), "FDF817451A60EB6F", "cDOiBC1n2QrkAY2P");

        const { success, data } = await sendWebNet(WebNetName.submit, {
            encryptedData: encrypt,
        }, {
            // isGet: false,
        });

        hideWaiting();

        if (!success) {
            return false;
        }

    }

}
