<template>
  <Image texture="waypoint" :x="waypoint.x" :y="waypoint.y" :visible="waypoint.visible" />
  <Sprite ref="sprite" texture="player" :x :y />
</template>

<script lang="ts" setup>
import { Image, onPreUpdate, refObj, Sprite, useScene } from 'phavuer'
import { ref } from 'vue'
import config from '@/config'

/**
 * 1 tile is 64x32
 * the map is 10x10
 * so the map is 640x320
 */
const props = defineProps({
  layer: Phaser.Tilemaps.TilemapLayer
})

const scene = useScene()

const pointer_tile = ref(undefined);
const waypoint = ref({
  visible: false,
  x: 0,
  y: 0,
})

const x = ref(0);
const y = ref(0);

const onPointerMove = (e: Phaser.Input.Pointer) => {
  const px = scene.cameras.main.worldView.x + e.x;
  const py = scene.cameras.main.worldView.y + e.y;

  pointer_tile.value = getTile(px, py, props.layer);
  waypoint.value.visible = true;

  if (pointer_tile.value !== undefined) {
    // Convert tile coordinates to world coordinates
    const worldPoint = props.layer.tileToWorldXY(pointer_tile.value.x, pointer_tile.value.y);
    waypoint.value.x = worldPoint.x;
    waypoint.value.y = worldPoint.y;
  }
};

onPreUpdate(() => {

})

scene.input.on(Phaser.Input.Events.POINTER_MOVE, onPointerMove);

function getTile (x: number, y: number, layer: Phaser.Tilemaps.TilemapLayer): Phaser.Tilemaps.Tile | undefined {
  const tile: Phaser.Tilemaps.Tile = layer.getTileAtWorldXY(x, y);
  console.log(x,y);
  if (tile) {
    console.log('tile', tile);
    return tile;
  } else {
    console.log('tile', tile);
    return undefined;
  }
}

function getTileAt (iX: number, iY: number, layer: Phaser.Tilemaps.TilemapLayer): Phaser.Tilemaps.Tile | undefined {
  const tile: Phaser.Tilemaps.Tile = layer.getTileAt(iX, iY);
  if (tile) return tile;
  else return undefined;
}

function getDepth(tile: Phaser.Tilemaps.Tile): number {
  return 32;
}
</script>