<template>
  <TilemapLayerC :tilemap="zone" :tileset="exampleTilesArray" :layerIndex="0" :cull-padding-x="10" :cull-padding-y="10" />

  <Controls :layer="tiles" />
  <!--  @TODO: inside asset manager we need to be able to set the originX and originY per individial asset -->
  <Container>
    <!--      <Image :texture="'wall1'" :x="pos.position_x" :y="pos.position_y" :originY="1.13" :originX="1" />-->
    <Image v-for="object in zoneObjects" :key="object.id" :texture="object.object" :x="object.position_x" :y="object.position_y" />
  </Container>

  <Toolbar :layer="tiles" @eraser="eraser" @pencil="pencil" @paint="paint" @save="save" />
  <Tiles v-if="((zoneEditorStore.tool === 'pencil' || zoneEditorStore.tool === 'eraser') && zoneEditorStore.drawMode === 'tile') || zoneEditorStore.tool === 'paint'" />
  <Objects v-if="(zoneEditorStore.tool === 'pencil' || zoneEditorStore.tool === 'eraser') && zoneEditorStore.drawMode === 'object'" />
  <ZoneSettings v-if="zoneEditorStore.isSettingsModalShown" />
</template>

<script setup lang="ts">
import config from '@/config'
import Tileset = Phaser.Tilemaps.Tileset
import TilemapLayer = Phaser.Tilemaps.TilemapLayer
import { Container, TilemapLayer as TilemapLayerC, useScene, Image } from 'phavuer'
import { onBeforeMount, onBeforeUnmount, onMounted, ref, toRaw, watch } from 'vue'
import Controls from '@/components/utilities/Controls.vue'
import { useSocketStore } from '@/stores/socket'
import Toolbar from '@/components/utilities/zoneEditor/Toolbar.vue'
import Tiles from '@/components/utilities/zoneEditor/Tiles.vue'
import { useZoneEditorStore } from '@/stores/zoneEditor'
import ZoneSettings from '@/components/utilities/zoneEditor/ZoneSettings.vue'
import { placeTile, tileToWorldXY } from '@/services/zone'
import { useAssetStore } from '@/stores/assets'
import Objects from '@/components/utilities/zoneEditor/Objects.vue'

const scene = useScene()
const socket = useSocketStore()
const zoneEditorStore = useZoneEditorStore()
const assetStore = useAssetStore()

// Tile tilemap
const zoneData = new Phaser.Tilemaps.MapData({
  width: zoneEditorStore.width,
  height: zoneEditorStore.height,
  tileWidth: config.tile_size.x,
  tileHeight: config.tile_size.y,
  orientation: Phaser.Tilemaps.Orientation.ISOMETRIC,
  format: Phaser.Tilemaps.Formats.ARRAY_2D
})

const zone = new Phaser.Tilemaps.Tilemap(scene, zoneData)
const tilesetImages: Tileset[] = []

type ZoneObject = {
  id: string
  object: string
  position_x: number
  position_y: number
}
const zoneObjects = ref<ZoneObject[]>([])

/**
 * Walk through object and add them to the zone as tilesetImages
 */
let tileCount = 1
toRaw(assetStore.assets).forEach((asset) => {
  if (asset.group !== 'tiles') return
  tilesetImages.push(zone.addTilesetImage(asset.key, asset.key, config.tile_size.x, config.tile_size.y, 0, 0, tileCount++) as Tileset)
})
tilesetImages.push(zone.addTilesetImage('blank_tile', 'blank_tile', config.tile_size.x, config.tile_size.y, 0, 0, 0) as Tileset)

const tiles = zone.createBlankLayer('tiles', tilesetImages, 0, config.tile_size.y) as TilemapLayer
const exampleTilesArray = Array.from({ length: zoneEditorStore.width }, () => Array.from({ length: zoneEditorStore.height }, () => 'blank_tile'))

placeTile(zone, tiles, 0, 0, 'blank_tile')

const pos = tileToWorldXY(tiles, 1, 1)
const pos2 = tileToWorldXY(tiles, 1, 2)
const pos3 = tileToWorldXY(tiles, 2, 1)
console.log(pos)

// Watch for changes in the zoneStore and update the layer
// watch(
//   () => zoneEditorStore.object,
//   () => {
//     // @TODO : change to zone for when loading other maps
//     zoneEditorStore.object.forEach((row, y) => row.forEach((tile, x) => layer.putTileAt(tile, x, y)))
//   },
//   { deep: true }
// )

// socket.connection.on('gm:zone_editor:zone:load', (data: Zone) => {
//   tileTilemap = generateTilemap(scene, data.width, data.height);
//   zoneEditorStore.setName(data.name)
//   zoneEditorStore.setWidth(data.width)
//   zoneEditorStore.setHeight(data.height)
// })

function eraser(tile: Phaser.Tilemaps.Tile) {
  if (zoneEditorStore.drawMode === 'tile') {
    placeTile(zone, tiles, tile.x, tile.y, 'blank_tile')
    zoneEditorStore.updateTile(tile.x, tile.y, 'blank_tile')
  }

  // if (zoneEditorStore.drawMode === 'wall') {
  //   walls.putTileAt(0, tile.x, tile.y)
  //   zoneEditorStore.updateWall(tile.x, tile.y, 0)
  // }
}

function pencil(tile: Phaser.Tilemaps.Tile) {
  if (zoneEditorStore.drawMode === 'tile') {
    if (!zoneEditorStore.selectedTile) return
    console.log('placing tile', tile.x, tile.y, zoneEditorStore.selectedTile)
    placeTile(zone, tiles, tile.x, tile.y, zoneEditorStore.selectedTile)
    // zoneEditorStore.setTiles(tile.x, tile.y, zoneEditorStore.selectedTile)
  }

  if (zoneEditorStore.drawMode === 'object') {
    // @TODO fix position
    if (zoneEditorStore.selectedObject === null) return
    if (config.development) console.log('placing object', tile.x, tile.y, zoneEditorStore.selectedObject)
    zoneObjects.value.push({
      id: Math.random().toString(10),
      object: zoneEditorStore.selectedObject,
      position_x: tileToWorldXY(tiles, tile.x, tile.y).position_x,
      position_y: tileToWorldXY(tiles, tile.x, tile.y).position_y
    })
  }
}

function paint(tile: Phaser.Tilemaps.Tile) {
  console.log('yoo')
  if (!zoneEditorStore.selectedTile) return
  console.log('placing tile', tile.x, tile.y, zoneEditorStore.selectedTile)
  exampleTilesArray.forEach((row, y) => row.forEach((tile, x) => placeTile(zone, tiles, x, y, zoneEditorStore.selectedTile)))
}

function save() {
  socket.connection.emit('gm:zone_editor:zone:save', {
    zoneId: socket.character.zoneId,
    name: zoneEditorStore.name,
    width: zoneEditorStore.width,
    height: zoneEditorStore.height,
    tiles: zoneEditorStore.tiles,
    objects: zoneEditorStore.objects
  })
}

watch(
  () => assetStore.assets,
  () => {
    console.log('re-loading assets', assetStore.assets)
    toRaw(assetStore.assets).forEach((asset) => {
      if (asset.type === 'link') {
        scene.load.image(asset.key, config.server_endpoint + '/assets' + asset.value + '.png')
      }
      if (asset.type === 'base64') {
        scene.textures.addBase64(asset.key, asset.value)
      }
    })

    scene.load.start()

    scene.load.once('complete', () => {
      console.log('assets re-loaded')
    })
  },
  { deep: true }
)

onBeforeMount(() => {
  exampleTilesArray.forEach((row, y) => row.forEach((tile, x) => placeTile(zone, tiles, x, y, 'blank_tile')))
  socket.connection.emit('gm:zone_editor:zone:request', { zoneId: socket.character.zoneId })
})

onBeforeUnmount(() => {
  zoneEditorStore.reset()
})

// center camera
const centerY = (zone.height * zone.tileHeight) / 2
const centerX = (zone.width * zone.tileWidth) / 2
scene.cameras.main.centerOn(centerX, centerY)

/**
 * Resources:
 * https://stackoverflow.com/questions/14488989/drawing-isometric-walls
 */
</script>
