<template>
  <q-card
    class="background: radial-gradient(circle, #35a2ff 0%, #014a88 100%) justify-start content-center items-center rounded-borders border-primary shadow-5 q-mb-xs"
    bordered
  >
    <header class="text-primary q-px-xs">
      <div class="col text-weight-bolder ellipsis">
        {{ event.type.name }}
      </div>

      <div v-if="event.description" class="col text-weight-medium" style="font-size: 10px">
        Info
        {{ event.description }}
      </div>
    </header>

    <div v-for="(job, index) in event.jobs" :key="index">
      <q-separator style="justify-start content-center" />
      <div class="text-weight-medium q-px-xs">
        {{ asHour(job.start) }} <template v-if="job.end">- {{ asHour(job.end) }}</template>
      </div>
      <div class="q-px-xs">
        {{ job.type.name }}
      </div>
      <div class="col-auto q-px-xs" style="font-size: 10px">
        {{ job.comment }}
      </div>
      <div>
        <q-select
          :key="refreshKey"
          v-model="job.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="job.required_services"
        >
        </q-select>
        <div class="row col-12 justify-end">
          <q-btn v-if="false" />
          <q-btn
            v-if="!isUserEnrolled(job) && !jobFull(job)"
            :key="refreshKey"
            flat
            color="primary"
            label="Eintragen"
            @click="enrollForJob(job)"
          />
          <q-btn
            v-if="isUserEnrolled(job)"
            :key="refreshKey"
            flat
            color="negative"
            label="Austragen"
            @click="signOutFromJob(job)"
          />
        </div>
      </div>
    </div>
  </q-card>
</template>

<script lang="ts">
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
import { defineComponent, ref, onBeforeMount, PropType } from 'vue';
import { useRouter } from 'vue-router';
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: 'Eventslot',
  components: {},
  props: {
    event: {
      required: true,
      type: Object as PropType<FG.Event>,
    },
  },

  setup(props) {
    const store = useScheduleStore();
    const mainStore = useMainStore();
    const userStore = useUserStore();
    const router = useRouter();
    const availableUsers = null;
    const refreshKey = ref<number>(0);

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

    function refresh() {
      router.go(0);
      refreshKey.value += 1;
    }

    function isUserEnrolled(job: FG.Job) {
      return (
        job.services.findIndex((service) => service.userid == mainStore.currentUser.userid) >= 0
      );
    }

    function jobFull(job: FG.Job) {
      return job.services.length >= job.required_services;
    }

    function userDisplay(userid: string) {
      return userStore.users.find((user) => (user.userid = userid))?.display_name;
    }

    async function enrollForJob(job: FG.Job) {
      const newService: FG.Service = {
        userid: mainStore.currentUser.userid,
        value: 1,
      };
      try {
        await store.updateEvent(props.event.id, job.id, { user: newService });
      } 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' }],
        });
      }
      refresh();
    }
    async function signOutFromJob(job: FG.Job) {
      const newService: FG.Service = {
        userid: mainStore.currentUser.userid,
        value: -1,
      };
      try {
        await store.updateEvent(props.event.id, job.id, { user: newService });
      } 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' }],
        });
      }
      refresh();
    }

    return {
      refreshKey,
      availableUsers,
      enrollForJob,
      isUserEnrolled,
      signOutFromJob,
      jobFull,
      userDisplay,
      refresh,
      asHour,
    };
  },
});
</script>

<style scoped></style>
