<script setup lang="ts">
import {Character, CharacterLabel, useCharactersStore} from "@/characters";
import {useRoute} from "vue-router";
import {computed, ref, watch, watchEffect} from "vue";
import log from "loglevel";
import {
  RuleBook,
  useCharacterRuleBooksStore,
  useRuleBooksStore
} from "@/rules";
import {isMain, Ledger, LedgerSelect, systemLedger, useLedgersStore} from "@/ledger";

type Bindings = { [key: string]: Ledger; };

const ruleBookStore = useRuleBooksStore();
const characterRuleBooksStore = useCharacterRuleBooksStore();
const charactersStore = useCharactersStore();
const ledgersStore = useLedgersStore();

const ledgersToUse = computed(() => [systemLedger, ...ledgersStore.ledgers.filter(isMain)]);

const character = ref<Character>();
const ruleBook = ref<RuleBook>();
const bindings = ref<Bindings>({});
const ledgerRefs = computed<string[]>(() => ruleBook.value?.ledgerRefs ?? [])

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

  if (characterId) {
    const characterRuleBook = characterRuleBooksStore.findByCharacterId(characterId);

    ruleBook.value = ruleBookStore.findById(characterRuleBook?.ruleBook.ruleBookId ?? '');
    bindings.value = Object.fromEntries(
      Object.entries(characterRuleBook?.bindings ?? {})
        .map(([key, id]) => [key, ledgersToUse.value.find(l => l.ledgerId === id) ?? systemLedger])
    );
  }
});

const save = () => {
  const characterId = character.value?.characterId;
  const ruleBookId = ruleBook.value?.ruleBookId;

  if (characterId && ruleBookId) {
    characterRuleBooksStore.setForCharacter(characterId, {
      ruleBookId,
      bindings: Object.fromEntries(
        Object.entries(bindings.value)
          .map(([key, ledger]) => [key, ledger.ledgerId])
      )
    })
  }
}

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 charactersStore.findById(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>
        <button @click="save">Save</button>
      </div>
    </div>
    <div class="flex-col border-b-1">
      Rule Book:
      <select class="me-2 mb-2 w-50" v-model="ruleBook">
        <option v-for="rb in ruleBookStore.ruleBooks" :key="rb.ruleBookId" :value="rb">{{ rb.name }}</option>
      </select>
    </div>
    <div class="flex-col border-b-1">
      Ledger Bindings:
      <div class="flex flex-wrap items-center mb-2 mt-2">
        <div class="me-2" v-for="ref in ledgerRefs" :ref="ref">
          <span class="me-1">{{ref}}:</span>
          <LedgerSelect :ledgers="ledgersToUse" :modelValue="bindings[ref] ?? systemLedger" @update:modelValue="value => { if (value) bindings[ref] = value }" />
        </div>
      </div>
    </div>
  </div>
</template>