<template>
  <MapTiles ref="mapTiles" @tileMap:create="tileMap = $event" />
  <PlacedMapObjects ref="mapObjects" v-if="tileMap" :tileMap="tileMap as Phaser.Tilemaps.Tilemap" />
  <MapEventTiles ref="eventTiles" v-if="tileMap" :tileMap="tileMap as Phaser.Tilemaps.Tilemap" />
</template>

<script setup lang="ts">
import MapEventTiles from '@/components/gameMaster/mapEditor/mapPartials/MapEventTiles.vue'
import MapTiles from '@/components/gameMaster/mapEditor/mapPartials/MapTiles.vue'
import PlacedMapObjects from '@/components/gameMaster/mapEditor/mapPartials/PlacedMapObjects.vue'
import { useMapEditorComposable } from '@/composables/useMapEditorComposable'
import { useScene } from 'phavuer'
import { onMounted, onUnmounted, shallowRef, useTemplateRef } from 'vue'

const tileMap = shallowRef<Phaser.Tilemaps.Tilemap>()
const mapEditor = useMapEditorComposable()

const scene = useScene()

const mapTiles = useTemplateRef('mapTiles')
const mapObjects = useTemplateRef('mapObjects')
const eventTiles = useTemplateRef('eventTiles')

function handlePointer(pointer: Phaser.Input.Pointer) {
  if (!mapTiles.value || !mapObjects.value || !eventTiles.value) return

  // Check if left mouse button is pressed
  if (!pointer.isDown) return

  // Check if shift is not pressed, this means we are moving the camera
  if (pointer.event.shiftKey) return

  // Check if draw mode is tile
  switch (mapEditor.drawMode.value) {
    case 'tile':
      mapTiles.value.handlePointer(pointer)
    case 'object':
      mapObjects.value.handlePointer(pointer)
    case 'teleport':
      eventTiles.value.handlePointer(pointer)
  }
}

onMounted(() => {
  scene.input.on(Phaser.Input.Events.POINTER_MOVE, handlePointer)
  scene.input.on(Phaser.Input.Events.POINTER_DOWN, handlePointer)
})

onUnmounted(() => {
  scene.input.off(Phaser.Input.Events.POINTER_MOVE, handlePointer)
  scene.input.off(Phaser.Input.Events.POINTER_DOWN, handlePointer)
  mapEditor.reset()
})
</script>
