<script setup lang="ts">
import { TransactionApiClient, type TransactionCategoryTree } from '@/api/transaction';
import { onMounted, ref, type Ref } from 'vue';


const model = defineModel<number | null>({ required: true })
defineProps<{ required?: boolean }>()
defineEmits<{ categorySelected: [TransactionCategoryTree | null] }>()
const categories: Ref<TransactionCategoryTree[]> = ref([])

onMounted(() => {
  const api = new TransactionApiClient()
  api.getCategoriesFlattened()
    .then(c => categories.value = c)
})

function getCategoryById(id: number): TransactionCategoryTree | null {
  for (const c of categories.value) {
    if (c.id === id) return c
  }
  return null
}
</script>
<template>
  <select v-model="model" @change="$emit('categorySelected', model === null ? null : getCategoryById(model))">
    <option v-for="category in categories" :key="category.id" :value="category.id">
      {{ "&nbsp;".repeat(4 * category.depth) + category.name }}
    </option>
    <option v-if="required !== true" :value="null" :selected="model === null">None</option>
  </select>
</template>
