<template>
  <div class="asset">
    <input class="input-cyan search-field" placeholder="Search..." />
  </div>
  <div class="asset add-new">
    <span class="asset-name">Upload new</span>
    <label for="upload-asset" class="file-upload">
      <input id="upload-asset" ref="tileUploadField" type="file" accept="image/png" multiple @change="handleFileUpload" />
      Choose file
    </label>
  </div>
  <a class="asset" v-for="(tile, index) in tiles" :key="index">
    <div class="asset-details" @click="emit('select_tile', tile)">
      <img :src="`${config.server_endpoint}/assets/tiles/${tile}`" />
      <span class="asset-name">{{ tile }}</span>
    </div>
  </a>
</template>

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

const socket = useSocketStore()
const tileUploadField = ref(null)
const tiles = ref()

const emit = defineEmits(['select_tile']);

const handleFileUpload = (e: Event) => {
  const files = (e.target as HTMLInputElement).files
  if (!files) return
  socket.connection.emit('gm:tile:upload', files, (response: boolean) => {
    if (!response) {
      console.error('Failed to upload tile')
      return
    }
    socket.connection.emit('gm:tile:list', {}, (response: string[]) => {
      tiles.value = response
    })
  })
}

onMounted(() => {
  socket.connection.emit('gm:tile:list', {}, (response: string[]) => {
    tiles.value = response
  })
})
</script>

<style lang="scss" scoped>

</style>