<template>
  <div class="asset add-new">
    <label for="upload-asset" class="file-upload">
      <input id="upload-asset" ref="tileUploadField" type="file" accept="image/png" multiple @change="handleFileUpload" />
      Upload tile(s)
    </label>
    <input class="input-cyan search-field" placeholder="Search..." />
  </div>
  <a class="asset" :class="{ active: assetManagerStore.selectedTile === tile }" v-for="(tile, index) in assetManagerStore.tileList" :key="index" @click="assetManagerStore.setSelectedTile(tile)">
    <div class="asset-details">
      <img :src="`${config.server_endpoint}/assets/tiles/${tile}`" alt="Tile" />
      <span class="asset-name">{{ tile }}</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'

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

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[]) => {
      assetManagerStore.setTileList(response)
    })
  })
}

onMounted(() => {
  socket.connection.emit('gm:tile:list', {}, (response: string[]) => {
    assetManagerStore.setTileList(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>
