<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 ObjectList from '@/components/gameMaster/mapEditor/partials/ObjectList.vue'
import TeleportModal from '@/components/gameMaster/mapEditor/partials/TeleportModal.vue'
import TileList from '@/components/gameMaster/mapEditor/partials/TileList.vue'
// Components
import Toolbar from '@/components/gameMaster/mapEditor/partials/Toolbar.vue'
import MapList from '@/components/gameMaster/mapEditor/partials/MapList.vue'
import MapSettings from '@/components/gameMaster/mapEditor/partials/MapSettings.vue'
import MapEventTiles from '@/components/gameMaster/mapEditor/mapPartials/MapEventTiles.vue'
import MapObjects from '@/components/gameMaster/mapEditor/mapPartials/MapObjects.vue'
import MapTiles from '@/components/gameMaster/mapEditor/mapPartials/MapTiles.vue'
import { useGameStore } from '@/stores/gameStore'
import { useMapEditorStore } from '@/stores/mapEditorStore'
import { onUnmounted, ref } from 'vue'

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

const tileMap = ref(null as Phaser.Tilemaps.Tilemap | null)

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

  // Clear objects, event tiles and tiles
  mapEditorStore.map.mapObjects = []
  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, mapId, effect, strength }) => ({ id, mapId, effect, strength })),
    mapEventTiles: mapEditorStore.map.mapEventTiles.map(({ id, mapId, type, positionX, positionY, teleport }) => ({ id, mapId, type, positionX, positionY, teleport })),
    mapObjects: mapEditorStore.map.mapObjects.map(({ id, mapId, objectId, depth, isRotated, positionX, positionY }) => ({ id, mapId, objectId, depth, isRotated, positionX, positionY }))
  }

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

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

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