<template>
  <MapTiles @tileMap:create="tileMap = $event" />
  <!--  <MapObjects v-if="tileMap" :tilemap="tileMap as Phaser.Tilemaps.Tilemap" />-->
  <MapEventTiles v-if="tileMap" :tilemap="tileMap as Phaser.Tilemaps.Tilemap" />

  <Toolbar @save="save" @clear="clear" />

  <MapList />
  <TileList />
  <ObjectList />

  <MapSettings />
  <TeleportModal />
</template>

<script setup lang="ts">
import { type Map } from '@/application/types'
import MapEventTiles from '@/components/gameMaster/mapEditor/mapPartials/MapEventTiles.vue'
import MapTiles from '@/components/gameMaster/mapEditor/mapPartials/MapTiles.vue'
import MapObjects from '@/components/gameMaster/mapEditor/mapPartials/PlacedMapObjects.vue'
import MapList from '@/components/gameMaster/mapEditor/partials/MapList.vue'
import ObjectList from '@/components/gameMaster/mapEditor/partials/MapObjectList.vue'
import MapSettings from '@/components/gameMaster/mapEditor/partials/MapSettings.vue'
import TeleportModal from '@/components/gameMaster/mapEditor/partials/TeleportModal.vue'
import TileList from '@/components/gameMaster/mapEditor/partials/TileList.vue'
import Toolbar from '@/components/gameMaster/mapEditor/partials/Toolbar.vue'
import { loadAllTilesIntoScene } from '@/composables/mapComposable'
import { useGameStore } from '@/stores/gameStore'
import { useMapEditorStore } from '@/stores/mapEditorStore'
import { useScene } from 'phavuer'
import { onBeforeMount, onUnmounted, shallowRef } from 'vue'

const gameStore = useGameStore()
const mapEditorStore = useMapEditorStore()
const scene = useScene()

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

function clear() {
  if (!mapEditorStore.map) return

  // Clear objects, event tiles and tiles
  mapEditorStore.map.placedMapObjects = []
  mapEditorStore.map.mapEventTiles = []
  mapEditorStore.triggerClearTiles()
}

function save() {
  if (!mapEditorStore.map) return

  const data = {
    mapId: mapEditorStore.map.id,
    name: mapEditorStore.mapSettings.name,
    width: mapEditorStore.mapSettings.width,
    height: mapEditorStore.mapSettings.height,
    tiles: mapEditorStore.map.tiles,
    pvp: mapEditorStore.map.pvp,
    mapEffects: mapEditorStore.map.mapEffects?.map(({ id, effect, strength }) => ({ id, effect, strength })) ?? [],
    mapEventTiles: mapEditorStore.map.mapEventTiles?.map(({ id, type, positionX, positionY, teleport }) => ({ id, type, positionX, positionY, teleport })) ?? [],
    placedMapObjects: mapEditorStore.map.placedMapObjects?.map(({ id, mapObject, depth, isRotated, positionX, positionY }) => ({ id, mapObject, depth, isRotated, positionX, positionY })) ?? []
  }

  if (mapEditorStore.isSettingsModalShown) {
    mapEditorStore.toggleSettingsModal()
  }

  gameStore.connection?.emit('gm:map:update', data, (response: Map) => {
    mapEditorStore.setMap(response)
  })
}

onUnmounted(() => {
  mapEditorStore.reset()
})
</script>