<template>
  <div class="object-manager">
    <div class="image-container relative p-2.5 flex items-center justify-center h-[300px]">
      <img class="max-h-[280px]" :src="objectImageUrl" :alt="'Object ' + selectedObject" />
      <div class="absolute left-0 bottom-0 w-full h-[1px] bg-cyan-200"></div>
    </div>
    <div class="modal-form asset-manager m-2.5 p-2.5 block">
      <form class="flex gap-2.5 flex-wrap" @submit.prevent>
        <div class="w-full flex flex-col mb-5">
          <label class="mb-1.5 font-titles" for="name">Name</label>
          <input class="input-cyan" type="text" name="name" placeholder="Wall #1" />
        </div>
        <div class="w-[48%] flex flex-col mb-5"> <!-- @TODO: find Tailwind alternative to use 50% and accomodate gap -->
          <label class="mb-1.5 font-titles" for="origin-x">Origin X</label>
          <input class="input-cyan" type="number" name="origin-x" placeholder="Origin X" />
        </div>
        <div class="w-[48%] flex flex-col mb-5"> <!-- @TODO: find Tailwind alternative to use 50% and accomodate gap -->
          <label class="mb-1.5 font-titles" for="origin-y">Origin Y</label>
          <input class="input-cyan" type="number" name="origin-y" placeholder="Origin Y" />
        </div>
        <button class="btn-cyan px-[15px] py-1.5 min-w-[100px]" type="button" @click="removeObject">Save</button>
        <button class="btn-bordeaux px-[15px] py-1.5 min-w-[100px]" type="button" @click="removeObject">Remove</button>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted } from 'vue'
import { useAssetManagerStore } from '@/stores/assetManager'
import { useSocketStore } from '@/stores/socket'
import config from '@/config'

const socket = useSocketStore()
const assetManagerStore = useAssetManagerStore()
const selectedObject = computed(() => assetManagerStore.selectedObject)
const objectImageUrl = computed(() => `${config.server_endpoint}/assets/objects/${selectedObject.value}.png`)
const objectDetails = computed(() => assetManagerStore.objectDetails)

function removeObject() {
  socket.connection.emit('gm:object:remove', { object: selectedObject.value }, (response: boolean) => {
    if (!response) {
      console.error('Failed to remove object')
      return
    }
    refreshObjectList()
  })
}

function refreshObjectList() {
  socket.connection.emit('gm:object:list', {}, (response: string[]) => {
    assetManagerStore.setObjectList(response)
    assetManagerStore.setSelectedObject('')
  })
}

onMounted(() => {
  if (!selectedObject.value) {
    return
  }
  socket.connection.emit('gm:object:details', { object: selectedObject.value }, (response: any) => {
    assetManagerStore.setObjectDetails(response)
  })
})

onBeforeUnmount(() => {
  assetManagerStore.setSelectedObject('')
})
</script>

<style lang="scss">

.asset-info {
  .object-manager {
    height: 100%;
    overflow: auto;
  }
}

</style>
