<template>
  <div>
    <div
      id="loading-screen"
      style="
        position: absolute;
        width: 100%;
        height: 100%;
        background: white;
        z-index: 1000;
        display: flex;
        align-items: center;
        justify-content: center;
      "
    >
      <img src="images/logo.png" alt="Loading..." id="loading-logo" />
    </div>
    <div id="phaser-container"></div>
  </div>
</template>

<script lang="ts">
import 'phaser';
// import 'phaser3-rex-plugins/templates/ui/ui-plugin';
// import 'phaser3-rex-plugins/templates/ui/ui-components';
import CreateScrollablePanel from './CreateScrollablePanel';
import { useKanvasoStore } from 'src/stores/kanvaso';
import { mapActions, mapState } from 'pinia';
import { objekto } from './mock';
import PreloadScene from './PreloadScene';
import BootScene from './BootScene';
import { KanvasojKanvaso, TreeNode } from 'src/types/stores/kanvaso';

declare const window: {
  objekto: TreeNode;
} & Window;

class EndlessCanvas extends Phaser.Scene {
  rexUI: any;
  constructor() {
    super({
      key: 'endless-canvas',
    });
  }

  preload() {
    this.load.scenePlugin(
      'rexuiplugin',
      'rexuiplugin.min.js',
      'rexUI',
      'rexUI',
    );
    this.load.image('icon', 'phaser/stretching_icon.png');
  }

  create(): void {
    this.cameras.main.setBackgroundColor('#abcdef');

    // Скрываем экран загрузки здесь, потому что на этом этапе preload уже завершен
    document.getElementById('loading-screen').style.display = 'none';

    if (window.objekto) {
      const topPanel = CreateScrollablePanel(this, window.objekto)
        .setPosition(400, 300)
        .layout();
      // .drawBounds(this.add.graphics(), 0xff0000)}
    }
  }
}

const config: Phaser.Types.Core.GameConfig = {
  type: Phaser.AUTO,
  parent: 'phaser-container',
  width: window.innerWidth < 600 ? window.innerWidth : window.innerWidth - 205,
  height:
    window.innerWidth < 600 ? window.innerHeight - 51 : window.innerHeight - 10,

  scale: {
    mode: Phaser.Scale.FIT,
    autoCenter: Phaser.Scale.CENTER_BOTH,
  },
  scene: EndlessCanvas,
  plugins: {
    // scene: [
    //   {
    //     key: 'rexUI',
    //     //@ts-ignore
    //     plugin: RexPlugins,
    //     mapping: 'rexUI',
    //   },
    //   // ...
    // ],
  },
};

export default {
  name: 'YourComponentName',
  data() {
    return {
      wsSubscribe: null,
    };
  },
  computed: {
    ...mapState(useKanvasoStore, ['getTree']),
    ...mapState(useKanvasoStore, {
      project: 'getKanvaso',
      kanvasoTree: 'getTree',
    }),
    // ...mapState(useCurrentUserStore, { userId: 'getUserId' }),

    currentProject() {
      return this.project ? this.project[0]?.node : null;
    },
    projectUuid() {
      return this.$route?.params?.uuid || '';
    },
  },
  watch: {
    getTree(val) {
      window.objekto = val;
    },
  },
  methods: {
    ...mapActions(useKanvasoStore, [
      'onGetKanvasoFull',
      'onEditKanvasoObjekto',
      'onEditKanvaso',
      'onEditKanvasoLigilo',
      'onGetKanvasoObjekto',
      'onKanvasoSubscribe',
    ]),
  },
  async mounted() {
    interface KanvasojKanvasoResult {
      data?: {
        kanvasojKanvaso?: KanvasojKanvaso;
      };
    }

    await this.onGetKanvasoFull({ uuid: this.projectUuid })
      .then((result: KanvasojKanvasoResult) => {
        if (!result.data.kanvasojKanvaso.edges.length) {
          throw new Error(result.toString());
        }
        this.onKanvasoSubscribe({
          kanvasoj: [this.currentProject.objId],
        }).then((data: any) => {
          this.wsSubscribe = data;
        });
      })
      .catch((err: any) => {
        console.log('error get kanvaso full :>> ', err);
        this.$router.replace({ name: 'projects' });
      });
    await this.onGetKanvasoObjekto({ kanvaso_Uuid: this.projectUuid });

    const resizeHandler = () => {
      game.scale.resize(window.innerWidth, window.innerHeight);
    };

    window.addEventListener('resize', resizeHandler);
    const game = new Phaser.Game(config);

    window.addEventListener('resize', function (event) {
      console.log('resize');
      game.scale.resize(
        window.innerWidth < 600 ? window.innerWidth : window.innerWidth - 205,
        window.innerWidth < 600
          ? window.innerHeight - 51
          : window.innerHeight - 10,
      );
    });
    // setInterval(() => {
    //   game.scale.resize(
    //     window.innerWidth < 600 ? window.innerWidth : window.innerWidth - 205,
    //     window.innerWidth < 600
    //       ? window.innerHeight - 51
    //       : window.innerHeight - 10,
    //   );
    // }, 100);
  },
  beforeUnmount() {
    this.wsSubscribe.unsubscribe();
    delete window.objekto;
  },
};
</script>
