import { makeAutoObservable, } from 'mobx';
import { LevelArr } from "@/pages/GamePage/Level/LevelConfig.ts";
import API from "@/api";
import { AESEncrypt } from "@/utils/Crypto.ts";
import { PageCtrl } from "@/core/ctrls/PageCtrl.tsx";
import HomePage from "@/pages/HomePage/HomePage.tsx";
import { ModalCtrl } from "@/core/ctrls/ModalCtrl.tsx";
import Settlechance from "@/components/settlechance/settlechance";
import Settlenochance from "@/components/settlenochance/settlenochance";

class GameStore {

  constructor() {
    makeAutoObservable(this);
  }

  gameInfo = {
    recordId: "",
    levelIndex: -1,
    levelIdxArr: [],
    countdownSeconds: 180,
    remainTipTimes: 0,
  }

  async start() {

    const { success, data } = await API.start();
    if (!success) return false;

    this.gameInfo.levelIdxArr = LevelArr.map((_, index) => index);
    this.gameInfo.levelIdxArr.sort(() => Math.random() - 0.5);
    this.gameInfo.levelIndex = -1;
    this.gameInfo.recordId = data.recordId;
    this.gameInfo.countdownSeconds = data.countdownSeconds;
    this.gameInfo.remainTipTimes = data.remainTipTimes

    return success;
  }

  async middleSubmit(score: number) {
    console.log(score);
    const param = AESEncrypt(JSON.stringify({
      recordId: this.gameInfo.recordId,
      score,
      timestamp: Date.now(),
    }), "7A2F4B8D1E6C3905", "cDOiBC1n2QrkAY2P");

    const { success, data } = await API.middleSubmit({ param });
    return success;
  }

  async submit(score: number) {
    console.log(score);
    const param = AESEncrypt(JSON.stringify({
      recordId: this.gameInfo.recordId,
      score,
      timestamp: Date.now(),
    }), "7A2F4B8D1E6C3905", "cDOiBC1n2QrkAY2P");

    const { success, data } = await API.middleSubmit({ param });
    if (!success) {
      PageCtrl.changePage(HomePage);
      return success;
    }

    if (data.drawChance) {
      ModalCtrl.showModal(Settlechance, { score, ...data });
    }else {
      ModalCtrl.showModal(Settlenochance, { score, ...data });
    }

    return success;
  }
}

export default (new GameStore());
