<template>
  <q-card-section>
    <div class="text-weight-medium q-px-xs">
      {{ asHour(modelValue.start) }}
      <template v-if="modelValue.end">- {{ asHour(modelValue.end) }}</template>
    </div>
    <div class="q-px-xs">
      {{ modelValue.type.name }}
    </div>
    <div class="col-auto q-px-xs" style="font-size: 10px">
      {{ modelValue.comment }}
    </div>
    <div>
      <q-select
        :model-value="modelValue.services"
        filled
        :option-label="(opt) => userDisplay(opt)"
        multiple
        disable
        use-chips
        stack-label
        label="Dienste"
        class="col-auto q-px-xs"
        style="font-size: 6px"
        counter
        :max-values="modelValue.required_services"
      >
      </q-select>
      <div class="row col-12 justify-end">
        <q-btn v-if="canEnroll" flat color="primary" label="Eintragen" @click="enrollForJob" />
        <q-btn v-if="isEnrolled" flat color="negative" label="Austragen" @click="signOutFromJob" />
      </div>
    </div>
  </q-card-section>
</template>

<script lang="ts">
import { defineComponent, onBeforeMount, computed, PropType } from 'vue';
import { Notify } from 'quasar';
import { asHour } from 'src/utils/datetime';
import { useUserStore } from 'src/plugins/user/store';
import { useMainStore } from 'src/store';
import { useScheduleStore } from 'src/plugins/schedule/store';

export default defineComponent({
  name: 'JobSlot',
  props: {
    modelValue: {
      required: true,
      type: Object as PropType<FG.Job>,
    },
    eventId: {
      required: true,
      type: Number,
    },
  },
  emits: { 'update:modelValue': (v: FG.Job) => !!v },
  setup(props, { emit }) {
    const store = useScheduleStore();
    const mainStore = useMainStore();
    const userStore = useUserStore();
    const availableUsers = null;

    onBeforeMount(async () => userStore.getUsers());

    function userDisplay(service: FG.Service) {
      return userStore.findUser(service.userid)?.display_name || service.userid;
    }

    const isEnrolled = computed(
      () =>
        props.modelValue.services.findIndex(
          (service) => service.userid == mainStore.currentUser.userid
        ) !== -1
    );

    const canEnroll = computed(() => {
      const is = isEnrolled.value;
      let sum = 0;
      props.modelValue.services.forEach((s) => (sum += s.value));
      return sum < props.modelValue.required_services && !is;
    });

    async function enrollForJob() {
      const newService: FG.Service = {
        userid: mainStore.currentUser.userid,
        value: 1,
      };
      try {
        const job = await store.updateJob(props.eventId, props.modelValue.id, { user: newService });
        emit('update:modelValue', job);
      } catch (error) {
        console.warn(error);
        Notify.create({
          group: false,
          type: 'negative',
          message: 'Fehler beim Eintragen als Dienst',
          timeout: 10000,
          progress: true,
          actions: [{ icon: 'mdi-close', color: 'white' }],
        });
      }
    }
    async function signOutFromJob() {
      const newService: FG.Service = {
        userid: mainStore.currentUser.userid,
        value: -1,
      };
      try {
        const job = await store.updateJob(props.eventId, props.modelValue.id, {
          user: newService,
        });
        emit('update:modelValue', job);
      } catch (error) {
        console.warn(error);
        Notify.create({
          group: false,
          type: 'negative',
          message: 'Fehler beim Austragen als Dienst',
          timeout: 10000,
          progress: true,
          actions: [{ icon: 'mdi-close', color: 'white' }],
        });
      }
    }

    return {
      availableUsers,
      enrollForJob,
      isEnrolled,
      signOutFromJob,
      canEnroll,
      userDisplay,
      asHour,
    };
  },
});
</script>

<style scoped></style>
