<template>
  <Image v-bind="imageProps" v-if="gameStore.isTextureLoaded(texture)" />
</template>

<script lang="ts" setup>
import type { MapCharacter, Sprite as SpriteT } from '@/application/types'
import { loadSpriteTextures } from '@/services/textureService'
import { CharacterHairStorage, CharacterTypeStorage, SpriteStorage } from '@/storage/storages'
import { useGameStore } from '@/stores/gameStore'
import { Image, useScene } from 'phavuer'
import { computed, onMounted, ref } from 'vue'

const props = defineProps<{
  mapCharacter: MapCharacter
}>()

const gameStore = useGameStore()
const scene = useScene()
const hairSpriteId = ref('')
const sprite = ref<SpriteT | null>(null)

const texture = computed(() => {
  const { rotation } = props.mapCharacter.character
  const direction = [0, 6].includes(rotation) ? 'back' : 'front'

  return `${hairSpriteId.value}-${direction}`
})

const isFlippedX = computed(() => [6, 4].includes(props.mapCharacter.character.rotation ?? 0))

const imageProps = computed(() => {
  const direction = [0, 6].includes(props.mapCharacter.character.rotation ?? 0) ? 'back' : 'front'
  const spriteAction = sprite.value?.spriteActions?.find((spriteAction) => spriteAction.action === direction)

  return {
    depth: 9999,
    originX: Number(spriteAction?.originX) ?? 0,
    originY: Number(spriteAction?.originY) ?? 0,
    flipX: isFlippedX.value,
    texture: texture.value
  }
})

onMounted(async () => {
  const characterHairStorage = new CharacterHairStorage()
  const spriteId = await characterHairStorage.getSpriteId(props.mapCharacter.character.characterHair!)
  if (!spriteId) return

  hairSpriteId.value = spriteId
  const spriteStorage = new SpriteStorage()
  sprite.value = await spriteStorage.get(spriteId)
  await loadSpriteTextures(scene, spriteId)
})
</script>
