<template>
  <div class="asset add-new relative p-2.5 cursor-pointer flex gap-y-2.5 gap-x-5 flex-wrap">
    <label for="upload-asset" class="file-upload bg-cyan bg-opacity-50 border border-solid border-white rounded drop-shadow-20 py-1.5 px-[15px] inline-flex hover:bg-cyan hover:cursor-pointer">
      <input class="hidden" id="upload-asset" ref="objectUploadField" type="file" accept="image/png" multiple @change="handleFileUpload" />
      Upload object(s)
    </label>
    <input class="input-cyan search-field w-full" placeholder="Search..." />
    <div class="absolute left-0 bottom-0 w-full h-[1px] bg-cyan-200"></div>
  </div>
  <a class="asset relative p-2.5 cursor-pointer" :class="{ active: assetManagerStore.selectedObject?.id === object.id }" v-for="(object, index) in assetManagerStore.objectList" :key="index" @click="assetManagerStore.setSelectedObject(object as Object)">
    <div class="asset-details flex items-center gap-2.5">
      <div class="h-[28px] w-[75px] max-w-[75px] flex justify-center">
        <img class="h-[28px]" :src="`${config.server_endpoint}/assets/objects/${object.id}.png`" alt="Object" />
      </div>
      <span class="asset-name flex-shrink-0">{{ object.name }}</span>
    </div>
    <div class="absolute left-0 bottom-0 w-full h-[1px] bg-cyan-200"></div>
  </a>
</template>

<script setup lang="ts">
import config from '@/config'
import { useSocketStore } from '@/stores/socket'
import { onMounted, ref } from 'vue'
import { useAssetManagerStore } from '@/stores/assetManager'
import { useAssetStore } from '@/stores/assets'
import type { Object } from '@/types'

const socket = useSocketStore()
const objectUploadField = ref(null)
const assetManagerStore = useAssetManagerStore()
const assetStore = useAssetStore()

const handleFileUpload = (e: Event) => {
  const files = (e.target as HTMLInputElement).files
  if (!files) return
  socket.connection.emit('gm:object:upload', files, (response: boolean) => {
    if (!response) {
      if (config.development) console.error('Failed to upload object')
      return
    }

    assetStore.fetchAssets()

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

onMounted(() => {
  socket.connection.emit('gm:object:list', {}, (response: Object[]) => {
    if (config.development) console.log(response)
    assetManagerStore.setObjectList(response)
  })
})
</script>