<template>
  <TilemapLayer v-if="isMapLoaded"  ref="tilemapLayer" :tilemap="map" :layerIndex="0" :cull-padding-x="10" :cull-padding-y="10" :tileset="serverMapData.tiles" />
<!--  <Controls :layer="layer" />-->
</template>

<script setup lang="ts">
/**
 * 1 tile is 64x32
 * the map is 10x10
 * so the map is 640x320
 */

import { refObj, TilemapLayer, useScene } from 'phavuer'
import Player from '@/components/sprites/player/Player.vue'
import config from '@/config'
import { onBeforeMount, onMounted, reactive, ref, type Ref, toRaw, watch } from 'vue'
import Tileset = Phaser.Tilemaps.Tileset
import Controls from '@/components/Controls.vue'
import { useSocketStore } from '@/stores/socket'

onBeforeMount(() => {
  socket.socket?.emit('get_map');
  socket.socket?.on('map', (map) => {
    // Get map from server
    serverMapData.value = map;
    isMapLoaded.value = true;

    map.tiles.forEach((row, y) => row.forEach((tile, x) => layer.putTileAt(tile, x, y)));
  });
});

const map = ref();
const mapData = ();


function loadMap() {

}

const isMapLoaded = ref(false);
const socket = useSocketStore();
const serverMapData = ref([]);
const scene = useScene()
const tilemapLayer = ref();

const map = new Phaser.Tilemaps.Tilemap(scene, mapData);
const tileset: (Tileset|null) = map.addTilesetImage('default', 'tiles');
const layer:TilemapLayer = map.createBlankLayer('layer', tileset, 0, config.tile_size.y);

// center camera
const centerY = (map.height * map.tileHeight) / 2
const centerX = (map.width * map.tileWidth) / 2
scene.cameras.main.centerOn(centerX, centerY)

/**
 * Resources
 * https://clintbellanger.net/articles/isometric_math/
 * https://gist.github.com/veleek/3be73dc61d5f5a80abc0f72c3ffe390e
 * https://gamedev.stackexchange.com/questions/116485/how-to-center-a-tilemap-in-phaser
 * https://github.com/Nulligma/phaser-isometric-test/blob/master/src/main.ts
 * https://github.com/neki-dev/isometric-snippets
 * https://github.com/itsezc/CycloneIO/blob/next/packages/client/games/HabboEngine.ts
 * https://github.com/daan93/phaser-isometric-demo/tree/main
 */
</script>