<template>
  <q-select v-model="selected" filled :label="label" :options="users" :option-label="showName" option-value="userid"
    map-options use-input input-debounce="0" @filter="filterFn" />
</template>

<script lang="ts">
import { computed, defineComponent, PropType, onBeforeMount, ref } from 'vue';
import { useUserStore } from '@flaschengeist/api';
import { DisplayNameMode } from '../models';

export default defineComponent({
  name: 'UserSelector',
  props: {
    label: { type: String, default: 'Benutzer' },
    modelValue: { default: undefined, type: Object as PropType<FG.User | undefined> },
  },
  emits: { 'update:modelValue': (user: FG.User) => !!user },
  setup(props, { emit }) {
    const userStore = useUserStore();

    onBeforeMount(() => {
      void userStore.getUsers(false);
      void userStore.getDisplayNameModeSetting(true);
    });

    const users = computed(() =>
      userStore.users.filter((user) => {
        let names = filter.value.toLowerCase().split(' ');
        if (names.length < 1) {
          return true;
        }
        if (names.length === 1) {
          let name = names[0];
          return (
            user.lastname.toLowerCase().includes(name) ||
            user.firstname.toLowerCase().includes(name)
          );
        }
        if (names.length === 2) {
          let name1 = names[0];
          let name2 = names[1];
          return (
            (user.lastname.toLowerCase().includes(name1) &&
              user.firstname.toLowerCase().includes(name2)) ||
            (user.lastname.toLowerCase().includes(name2) &&
              user.firstname.toLowerCase().includes(name1))
          );
        }
        return true;
      })
    );
    const filter = ref<string>('');
    const filterFn = (val: string, update: () => void) => {
      filter.value = val;
      update();
    };
    const selected = computed({
      get: () => props.modelValue,
      set: (value: FG.User | undefined) => (value ? emit('update:modelValue', value) : undefined),
    });
    function showName(user: FG.User) {
      switch (userStore.userSettings.display_name) {
        case DisplayNameMode.DISPLAYNAME:
          return user.display_name;
        case DisplayNameMode.FIRSTNAME:
          return user.firstname;
        case DisplayNameMode.LASTNAME:
          return user.lastname;
        case DisplayNameMode.FIRSTNAME_LASTNAME:
          return `${user.firstname} ${user.lastname}`;
        case DisplayNameMode.LASTNAME_FIRSTNAME:
          return `${user.lastname}, ${user.firstname}`;
      }
    }

    return {
      selected,
      users,
      filterFn,
      showName,
    };
  },
});
</script>
