<template>
  <q-card class="q-mx-xs q-mt-sm rounded-borders shadow-5" bordered>
    <q-spinner-rings
      v-if="serviceNeeded"
      size="100%"
      style="max-height: min(3vw, 3em); max-width: min(3vw, 3em); position: absolute"
      color="warning"
    />
    <q-card-section class="text-primary q-pa-xs" style="font-size: clamp(1em, 1.5vw, 1.6em)">
      <div class="text-weight-bolder text-center">
        {{ event.type.name }}<template v-if="event.name">: </template
        ><span style="font-size: 0.9em">
          {{ event.name }}
        </span>
      </div>

      <div v-if="event.description" class="text-weight-medium" style="font-size: 0.75em">
        {{ event.description }}
      </div>
    </q-card-section>
    <q-separator />
    <q-card-section class="q-pa-xs">
      <!-- Jobs -->
      <JobSlot
        v-for="(job, index) in event.jobs"
        :key="index"
        v-model="event.jobs[index]"
        class="col q-my-xs"
        :event-id="event.id"
      />
    </q-card-section>
    <q-card-actions v-if="canEdit || canDelete" vertical align="center">
      <q-btn
        v-if="canEdit"
        color="secondary"
        flat
        label="Bearbeiten"
        style="min-width: 95%"
        @click="edit"
      />
      <q-btn
        v-if="canDelete"
        color="negative"
        flat
        label="Löschen"
        style="min-width: 95%"
        @click="remove"
      />
    </q-card-actions>
  </q-card>
</template>

<script lang="ts">
import { defineComponent, computed, PropType } from 'vue';
import { hasPermission } from 'src/utils/permission';
import { PERMISSIONS } from 'src/plugins/events/permissions';
import JobSlot from './JobSlot.vue';

export default defineComponent({
  name: 'Eventslot',
  components: { JobSlot },
  props: {
    modelValue: {
      required: true,
      type: Object as PropType<FG.Event>,
    },
  },
  emits: {
    'update:modelValue': (val: FG.Event) => !!val,
    removeEvent: (val: number) => typeof val === 'number',
    editEvent: (val: number) => !!val,
  },
  setup(props, { emit }) {
    const canDelete = computed(() => hasPermission(PERMISSIONS.DELETE));
    const canEdit = computed(
      () =>
        hasPermission(PERMISSIONS.EDIT) &&
        (props.modelValue?.end || props.modelValue.start) > new Date()
    );
    const event = computed({
      get: () => props.modelValue,
      set: (v) => emit('update:modelValue', v),
    });

    const serviceNeeded = computed(() =>
      props.modelValue.jobs.some(
        (job) =>
          job.required_services >
          job.services.reduce((p, c) => ((c.value += p.value) && c) || c, { value: 0 }).value
      )
    );

    function remove() {
      emit('removeEvent', props.modelValue.id);
    }
    function edit() {
      emit('editEvent', props.modelValue.id);
    }

    return {
      canDelete,
      canEdit,
      edit,
      event,
      remove,
      serviceNeeded,
    };
  },
});
</script>

<style scoped></style>
