<template>
  <div class="asset add-new">
    <label for="upload-asset" class="file-upload">
      <input id="upload-asset" ref="objectUploadField" type="file" accept="image/png" multiple @change="handleFileUpload" />
      Upload object(s)
    </label>
    <input class="input-cyan search-field" placeholder="Search..." />
  </div>
  <a class="asset" :class="{ active: assetManagerStore.selectedObject === object.id }" v-for="(object, index) in assetManagerStore.objectList" :key="index" @click="assetManagerStore.setSelectedObject(object.id)">
    <div class="asset-details">
<!--      @TODO make all img have same width so text aligns nicely -->
      <img :src="`${config.server_endpoint}/assets/objects/${object.id}.png`" alt="Object" />
      <span class="asset-name">{{ object.name }}</span>
    </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 type { Object } from '@/types'

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

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
    }
    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>

<style lang="scss" scoped>
@import '@/assets/scss/main';

.asset {
  cursor: pointer;

  &.add-new {
    display: flex;
    gap: 10px 20px;
    flex-wrap: wrap;
    .asset-name {
      flex-shrink: 0;
    }
  }
  .search-field {
    width: calc(100% - 20px);
  }
  .file-upload {
    background-color: rgba($cyan, 0.5);
    border: 1px solid $white;
    border-radius: 5px;
    text-shadow: 0 3px 6px rgba($black, 0.2);
    padding: 6px 15px;
    display: inline-flex;

    &:hover {
      background-color: $cyan;
      cursor: pointer;
    }
    input[type='file'] {
      display: none;
    }
  }
}
</style>
