import React from 'react';
import { observer } from 'mobx-react';
import store from "@/store/store.ts";

import styles from "./GamePage.module.less";
import { Application, Assets, Sprite, Ticker } from "pixi.js";
import { Game } from "./Game.ts";
import { initBundle } from "@/core/pixi/Helper.ts";
import { Tween } from "@/core/tween";
import "@/core/pixi/base/mix.ts";

import { initDevtools } from '@pixi/devtools';
import { Button } from "@grace/ui";
import { PageCtrl } from "@/core/ctrls/PageCtrl.tsx";
import gameStore from "@/store/gameStore.ts";

import.meta.env.DEV && initDevtools({});

import bgImg from "../../assets/GamePage/bg.jpg";
import { ModalCtrl } from "@/core/ctrls/ModalCtrl.tsx";
import TipPanel from "@/panels/TipPanel/TipPanel.tsx";
import { LevelArr } from "@/pages/GamePage/Level/LevelConfig.ts";

export function getApp(): Application {
  return window["__app"];
}

@observer
class GamePage extends React.Component<any, any> {

  gameCanvas: HTMLCanvasElement = null;
  gameDiv: HTMLDivElement = null;
  app: Application = null;
  game: Game = null;

  async componentDidMount() {
    await initBundle();
    await this.initStage();
  }

  componentWillUnmount() {
    Tween.removeAllTweens();
    this.app.ticker.remove(this.onUpdate);
    this.game.destroy({
      children: true,
      texture: false,
      textureSource: false,
    });
  }

  async initStage() {

    // if (!gameCanvas) {
    //   gameCanvas = document.createElement("canvas");
    //   gameCanvas.className = styles.gameCanvas;
    // }
    //
    // this.gameDiv.appendChild(gameCanvas);

    // if (!window["__app"]) {
    const app = this.app = window["__app"] = new Application();
    await app.init({
      canvas: this.gameCanvas,
      width: 750,
      height: 1624,
      powerPreference: "high-performance",
      // resolution: Math.min(window.devicePixelRatio, 2) || 1,
      resolution: 1,
      preference: "webgl",
      webgl: {
        backgroundAlpha: 0,
        // preserveDrawingBuffer: true,
        // antialias: true,
        powerPreference: "high-performance",
      },
      eventMode: "static",
    });
    app.renderer.accessibility.destroy();
    // }

    // const app = this.app = window["__app"];


    console.time("loadBundle");
    await Assets.loadBundle("Game");
    console.timeEnd("loadBundle");

    const bg = this.app.stage.addChild(new Sprite());
    Assets.load(bgImg).then((texture) => bg.texture = texture);

    this.app.ticker.add(this.onUpdate);

    this.game = app.stage.addChild(new Game());

  }

  onUpdate = (time: Ticker) => {
    Tween.flush();
    this.game.onUpdate(time);
  };

  clickBack = () => {
    PageCtrl.backPage();
  }

  clickTip = () => {
    const { levelIndex, levelIdxArr } = gameStore.gameInfo;
    const levelIdx = levelIdxArr[levelIndex];
    const { tip, cls } = LevelArr[levelIdx];
    ModalCtrl.showModal(TipPanel, { tip });
  }

  render() {
    const {} = store.indexData;
    const { levelIndex, levelIdxArr } = gameStore.gameInfo;

    const titleSrc = new URL(
      `../../assets/GamePage/title/title${(levelIndex + 1) || 1}.png?x-oss-process=image/format,webp`,
      import.meta.url
    ).href;

    return <div className={styles.root} ref={(el) => this.gameDiv = el}>

      <canvas className={styles.gameCanvas} ref={(el) => this.gameCanvas = el}/>

      <div className={styles.cd}>180s</div>
      <img src={titleSrc} className={styles.title}/>
      <Button className={styles.tipBtn} onClick={this.clickTip}/>
      <Button className={styles.backBtn} onClick={this.clickBack}/>
    </div>;
  }
}

export default GamePage;
