import mobx from "mobx";
import store from "db://assets/Scripts/store/store";
import { creditsCost, sendWebNet, WebNetName } from "db://assets/Scripts/Utils/WebNet/WebNet";
import { showPanel } from "db://assets/core/Module/UIFast";
import { SucPanel } from "db://assets/Scripts/Panels/SucPanel";
import { OverPanel } from "db://assets/Scripts/Panels/OverPanel";

const { makeAutoObservable } = mobx;

export interface IStartInfo {
    level: number,
    startId: string,
    shareUnlocked: boolean,
}

class GameStore {

    startInfo: IStartInfo = {
        level: 0,
        startId: "",
        shareUnlocked: false,
    }

    async start() {

        const { freeTimes, gameCreditsEach } = store.homeInfo;

        const params: { ticketNum?: string } = {};

        if (freeTimes <= 0) {
            const { success, ticket } = await creditsCost("main", "start", "deduct_credits_desc", gameCreditsEach);
            if (!success) return false;
            params.ticketNum = ticket;
        }

        const { success, data } = await sendWebNet(WebNetName.start, params);

        if (!success) return false;

        this.startInfo = data;
        this.startInfo.level = 0;
        this.startInfo.shareUnlocked = false;

        return success;
    }

    async unlockPark(type: "share" | "credits" | "green") {

        const { startId, level } = this.startInfo;

        const params: any = {
            startId,
            level,
            type: type == "share" ? 1 : (type == "credits" ? 3 : 2),
        }

        if (type === "credits") {
            const { success, ticket } = await creditsCost("main", "unlockPark", "deduct_credits_desc", 1000);
            if (!success) return false;
            params.ticketNum = ticket;
        }

        const { success, data } = await sendWebNet(WebNetName.unlockPark, params);

        if (!success) return false;

        return success;
    }

    async middleSubmit() {

        const { startId, level } = this.startInfo;

        const { success, data } = await sendWebNet(WebNetName.middleSubmit, {
            startId,
            level,
        });

        if (!success) return false;
    }

    async submit(suc: boolean) {

        const { startId, level } = this.startInfo;

        const { success, data } = await sendWebNet(WebNetName.finalSubmit, {
            startId,
            level: suc ? level : level - 1,
        });

        if (!success) return false;

        await store.updateIndex();

        if (data.boxNum) {
            showPanel(SucPanel, data);
        } else {
            showPanel(OverPanel, data);
        }
    }
}


const gameStore: GameStore = makeAutoObservable(new GameStore());

export default gameStore;
