import type { Map, MapCharacter, UUID } from '@/application/types'
import { defineStore } from 'pinia'

export const useMapStore = defineStore('map', {
  state: () => {
    return {
      mapId: '',
      characters: [] as MapCharacter[],
      characterLoaded: false
    }
  },
  getters: {
    getCharacterById: (state) => {
      return (id: UUID) => state.characters.find((char) => char.character.id === id)
    },
    getCharacterCount: (state) => {
      return state.characters.length
    }
  },
  actions: {
    setMapId(mapId: string) {
      this.mapId = mapId
    },
    setCharacters(characters: MapCharacter[]) {
      this.characters = characters
    },
    addCharacter(character: MapCharacter) {
      this.characters.push(character)
    },
    updateCharacterProperty<K extends keyof MapCharacter>(characterId: string, property: K, value: MapCharacter[K]) {
      const character = this.characters.find((char) => char.character.id === characterId)
      if (character) {
        character[property] = value
      }
    },
    removeCharacter(characterId: UUID) {
      this.characters = this.characters.filter((char) => char.character.id !== characterId)
    },
    setCharacterLoaded(loaded: boolean) {
      this.characterLoaded = loaded
    },
    updateCharacterPosition(data: { characterId: UUID; positionX: number; positionY: number; rotation: number; isMoving: boolean }) {
      const character = this.characters.find((char) => char.character.id === data.characterId)
      if (character) {
        character.character.positionX = data.positionX
        character.character.positionY = data.positionY
        character.character.rotation = data.rotation
        character.isMoving = data.isMoving
      }
    },
    reset() {
      this.mapId = ''
      this.characters = []
      this.characterLoaded = false
    }
  }
})
