<template>
  <Image :depth="2" texture="waypoint" :x="waypoint.x" :y="waypoint.y" :visible="waypoint.visible" />
</template>

<script setup lang="ts">
import { Image, useScene } from 'phavuer'
import { onBeforeUnmount, ref, watch } from 'vue'
import config from '@/config'
import { getTile, tileToWorldXY } from '@/services/zone'
import { useZoneStore } from '@/stores/zone'
import { useZoneEditorStore } from '@/stores/zoneEditor'

const zoneStore = useZoneStore()
const zoneEditorStore = useZoneEditorStore()
const scene = useScene()
const props = defineProps({
  layer: Phaser.Tilemaps.TilemapLayer
})
const waypoint = ref({
  visible: false,
  x: 0,
  y: 0
})

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

  const pointer_tile = getTile(px, py, props.layer) as Phaser.Tilemaps.Tile
  if (!pointer_tile) {
    waypoint.value.visible = false
    return
  }

  waypoint.value.visible = true

  // Convert tile coordinates to world coordinates
  const worldPoint = tileToWorldXY(props.layer, pointer_tile.x, pointer_tile.y)
  waypoint.value.x = worldPoint.position_x
  waypoint.value.y = worldPoint.position_y + config.tile_size.y + 15
}

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

// Zone camera system
function dragZone(pointer: Phaser.Input.Pointer) {
  if (!pointer.isDown) return
  cam.scrollX -= (pointer.x - pointer.prevPosition.x) / cam.zoom
  cam.scrollY -= (pointer.y - pointer.prevPosition.y) / cam.zoom
}
let cam = scene.cameras.main
scene.input.on(Phaser.Input.Events.POINTER_MOVE, dragZone)

watch(
  () => zoneEditorStore.tool,
  () => {
    // @TODO : change to zone for when loading other maps
    if (zoneEditorStore.tool === 'move') {
      scene.input.on(Phaser.Input.Events.POINTER_MOVE, dragZone)
    } else {
      scene.input.off(Phaser.Input.Events.POINTER_MOVE, dragZone)
    }
  },
  { deep: true }
)

// if ctrl is pressed and mouse is down , then drag the zone
scene.input.on(Phaser.Input.Events.POINTER_DOWN, (pointer: Phaser.Input.Pointer) => {
  if (pointer.event.altKey) {
    scene.input.on(Phaser.Input.Events.POINTER_MOVE, dragZone)
  } else if (zoneEditorStore.tool !== 'move') {
    scene.input.off(Phaser.Input.Events.POINTER_MOVE, dragZone)
  }
})

/**
 * Zoom in and out
 */
scene.input.on(Phaser.Input.Events.POINTER_WHEEL, (pointer: Phaser.Input.Pointer, gameObjects: Phaser.GameObjects.GameObject[], deltaX: number, deltaY: number) => {
  if (pointer.event.altKey) {
    scene.scale.setZoom(scene.scale.zoom - deltaY * 0.01)
    cam = scene.cameras.main
  }
})

// Unload funcs
onBeforeUnmount(() => {
  scene.input.off(Phaser.Input.Events.POINTER_MOVE, onPointerMove)
  scene.input.off(Phaser.Input.Events.POINTER_MOVE, dragZone)
})
</script>
