<template>
  <div class="flex flex-col justify-center items-center h-dvh relative">
    <div v-if="!isLoaded" class="w-20 h-20 rounded-full border-4 border-solid border-gray-300 border-t-transparent animate-spin"></div>
    <button v-else @click="continueBtnClick" class="w-20 h-20 rounded-full bg-gray-500 flex items-center justify-center hover:bg-gray-600 transition-colors">
      <svg xmlns="http://www.w3.org/2000/svg" class="h-10 w-10 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
      </svg>
    </button>
    <div v-if="!isLoaded" class="text-center mt-6">
      <h1 class="text-2xl font-bold">Loading...</h1>
      <p class="text-gray-400">Please wait while we load the assets.</p>
    </div>
  </div>
</template>

<script setup lang="ts" async>
import { onMounted, ref } from 'vue'
import config from '@/config'
import type { AssetT as ServerAsset } from '@/types'
import { useAssetManager } from '@/utilities/assetManager'
import { useGameStore } from '@/stores/gameStore'

/**
 * This component downloads all assets from the server and
 * stores them in the asset manager.
 */

const gameStore = useGameStore()
const assetManager = useAssetManager
const isLoaded = ref(false)

async function getAssets() {
  return fetch(config.server_endpoint + '/assets/')
    .then((response) => {
      if (!response.ok) throw new Error('Failed to fetch assets')
      console.log(response)
      return response.json()
    })
    .catch((error) => {
      console.error('Error fetching assets:', error)
      return false
    })
}

async function loadAssetsIntoAssetManager(assets: ServerAsset[]): Promise<void> {
  for (const asset of assets) {
    // Check if the asset is already loaded
    const existingAsset = await assetManager.getAsset(asset.key)

    // Check if the asset needs to be updated
    if (!existingAsset || new Date(asset.updatedAt) > new Date(existingAsset.updatedAt)) {
      // Check if the asset is already loaded, if so, delete it
      if (existingAsset) {
        await assetManager.deleteAsset(asset.key)
      }

      // Add the asset to the asset manager
      await assetManager.downloadAsset(asset.key, asset.url, asset.group, asset.updatedAt, asset.frameCount, asset.frameWidth, asset.frameHeight)
    }
  }
}

function continueBtnClick() {
  gameStore.isAssetsLoaded = true
}

onMounted(async () => {
  const assets = await getAssets()
  if (assets) {
    await loadAssetsIntoAssetManager(assets)
    isLoaded.value = true
  }
})
</script>
