<script setup lang="ts">
import {Character, CharacterLabel, useCharactersStore} from "@/characters";
import {useRoute} from "vue-router";
import {ref, watch, watchEffect} from "vue";
import log from "loglevel";
import {activityTypes, findByCharacterId, RuleBook, RuleSetInput} from "@/rules";

const {findById: findCharacterById} = useCharactersStore();
const character = ref<Character>();

const ruleBook = ref<RuleBook>();

watchEffect(async () => {
  const characterId = character.value?.characterId;

  if (characterId) {
    ruleBook.value = await findByCharacterId(characterId);
  }
});

watch(useRoute(), async route => {
  if (route.params.characterId) {
    const id = parseInt(typeof route.params.characterId === 'string' ? route.params.characterId : route.params.characterId[0]);

    character.value = await findCharacterById(id);
    log.info('Loaded character:', character.value);
  } else {
    character.value = undefined;
    log.info('No character to load');
  }
}, { immediate: true })
</script>

<template>
  <div v-if="character" class="grid mb-2 mt-4">
    <div class="mb-2 border-b-1 flex">
      <CharacterLabel class="flex grow mb-2" :character="character" :size="64" />
    </div>
    <div v-if="ruleBook" class="flex-col">
      <div class="flex-col grow border-b-1" v-for="activityType in activityTypes" :key="activityType">
        <span>{{ activityType }}</span>
        <RuleSetInput v-model="ruleBook.ruleSets[activityType]" />
      </div>
    </div>
  </div>
</template>