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

import styles from "./Top.module.less";
import classNames from "classnames";
import { Application, Assets, Ticker } from "pixi.js";
import { Game } from "@/pages/HomePage/Top/Game.ts";
import { initBundle } from "@/pages/HomePage/Top/Helper.ts";
import { Tween } from "@/core/tween";
import { SvgaPlayer } from "@grace/svgaplayer";

import handSvga from "@/assets/svga/3牌子转动.svga";

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

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

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

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

  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,
        backgroundColor: "rgba(0, 0, 0, 0)",
        width: 750,
        height: 1000,
        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);
  };

  render() {
    const {} = store.indexData
    return <div className={styles.top} ref={(el) => this.gameDiv = el}>
      <canvas className={styles.gameCanvas} ref={(el) => this.gameCanvas = el}/>
      <SvgaPlayer className={styles.handSvga} src={handSvga}/>
      <div className={styles.credits}>积分:<span>200</span>/300</div>
    </div>;
  }
}

export default Top;
