<template>
  <q-chip
    :removable="removeable"
    :color="modelValue.is_backup ? 'grey' : undefined"
    @remove="remove"
  >
    <q-tooltip>{{ displayName }} ({{ serviceValue }}x)</q-tooltip>
    <user-avatar :model-value="modelValue.userid">
      <slot v-if="modelValue.is_backup">
        <q-icon v-if="modelValue.is_backup" name="mdi-eye-off" />
      </slot>
    </user-avatar>
    <div class="ellipsis">{{ displayName }}</div>
    <q-badge v-if="modelValue.value !== 1" :label="serviceValue" style="margin-left: 0.25em" />
    <slot />
  </q-chip>
</template>

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

import { UserAvatar } from '@flaschengeist/api/components';

export default defineComponent({
  name: 'ServiceUserChip',
  components: { UserAvatar },
  props: {
    modelValue: {
      type: Object as PropType<FG.Service>,
      required: true,
    },
    removeable: {
      type: Boolean,
      default: false,
    },
  },
  emits: ['remove'],
  setup(props, { emit }) {
    const userStore = useUserStore();

    const user = ref<FG.User>();

    onBeforeMount(async () => {
      user.value = await userStore.getUser(props.modelValue.userid);
    });

    watch(
      () => props.modelValue,
      async () => (user.value = await userStore.getUser(props.modelValue.userid))
    );

    const displayName = computed(() => user.value?.display_name || '...');
    const serviceValue = computed(() =>
      props.modelValue.value.toFixed(Number.isInteger(props.modelValue.value) ? 0 : 1)
    );

    return {
      displayName,
      remove: () => emit('remove', props.modelValue),
      serviceValue,
    };
  },
});
</script>

<style></style>
