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

import styles from "./GamePage.module.less";
import { Application, Assets, 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.meta.env.DEV && initDevtools({});

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");

    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 = () => {
  }

  render() {
    const {} = store.indexData;
    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={new URL(`@/assets/GamePage/title/title1.png?x-oss-process=image/format,webp`, import.meta.url).href}
        className={styles.title}
      />
      <Button className={styles.tipBtn} onClick={this.clickTip}/>
      <Button className={styles.backBtn} onClick={this.clickBack}/>
    </div>;
  }
}

export default GamePage;
