<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 '@/composables/gameComposable'
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
  currentX: number
  currentY: number
}>()

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: 1,
    originX: Number(spriteAction?.originX) ?? 0,
    originY: Number(spriteAction?.originY) ?? 0,
    flipX: isFlippedX.value,
    texture: texture.value,
    y: props.currentY,
    x: props.currentX
  }
})

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>
