<template>
  <q-card>
    <q-form @submit="save()" @reset="reset">
      <q-card-section class="fit row justify-start content-center items-center">
        <div class="text-h6 col-xs-12 col-sm-6 q-pa-sm">
          Veranstaltung <template v-if="modelValue">bearbeiten</template
          ><template v-else>erstellen</template>
        </div>
        <q-select
          :model-value="template"
          filled
          label="Vorlage"
          class="col-xs-12 col-sm-6 q-pa-sm"
          :options="templates"
          option-label="name"
          map-options
          clearable
          :disable="templates.length == 0"
          @update:model-value="fromTemplate"
          @clear="reset()"
        />
        <q-input
          v-model="event.name"
          class="col-xs-12 col-sm-6 q-pa-sm"
          label="Name"
          type="text"
          filled
        />
        <q-select
          v-model="event.type"
          filled
          use-input
          label="Veranstaltungstyp"
          input-debounce="0"
          class="col-xs-12 col-sm-6 q-pa-sm"
          :options="eventtypes"
          option-label="name"
          option-value="id"
          emit-value
          map-options
          clearable
          :rules="[notEmpty]"
        />
        <IsoDateInput
          v-model="event.start"
          class="col-xs-12 col-sm-6 q-pa-sm"
          label="Veranstaltungsbeginn"
          :rules="[notEmpty]"
        />
        <IsoDateInput
          v-model="event.end"
          class="col-xs-12 col-sm-6 q-pa-sm"
          label="Veranstaltungsende"
          :rules="[afterStart]"
        />
        <q-input
          v-model="event.description"
          class="col-12 q-pa-sm"
          label="Beschreibung"
          type="textarea"
          filled
        />
      </q-card-section>
      <q-card-section v-if="event.is_template !== true && modelValue === undefined">
        <q-btn-toggle
          v-model="recurrent"
          spread
          no-caps
          :options="[
            { label: 'Einmalig', value: false },
            { label: 'Wiederkehrend', value: true },
          ]"
        />
        <RecurrenceRule v-if="!!recurrent" v-model="recurrenceRule" />
      </q-card-section>
      <q-separator />
      <q-card-section>
        <q-btn color="primary" label="Schicht hinzufügen" @click="addJob()" />
      </q-card-section>
      <q-card-section v-for="(job, index) in event.jobs" :key="index">
        <edit-job-slot v-model="event.jobs[index]" @remove-job="removeJob(index)" />
      </q-card-section>
      <q-card-actions align="around">
        <q-card-actions align="left">
          <q-btn v-if="!template" color="secondary" label="Neue Vorlage" @click="save(true)" />
          <q-btn v-else color="negative" label="Vorlage löschen" @click="removeTemplate" />
        </q-card-actions>
        <q-card-actions align="right">
          <q-btn label="Zurücksetzen" type="reset" />
          <q-btn color="primary" type="submit" label="Speichern" />
        </q-card-actions>
      </q-card-actions>
    </q-form>
  </q-card>
</template>

<script lang="ts">
import { notEmpty } from '@flaschengeist/api';
import { IsoDateInput } from '@flaschengeist/api/components';

import { useEventStore } from '../../store';
import { emptyEvent, emptyJob, EditableEvent } from '../../store/models';

import { date, ModifyDateOptions } from 'quasar';
import { computed, defineComponent, PropType, ref, onBeforeMount } from 'vue';

import EditJobSlot from './EditJobSlot.vue';
import RecurrenceRule from './RecurrenceRule.vue';

export default defineComponent({
  name: 'EditEvent',
  components: { IsoDateInput, EditJobSlot, RecurrenceRule },
  props: {
    modelValue: {
      required: false,
      default: () => undefined,
      type: Object as PropType<FG.Event | undefined>,
    },
    date: {
      required: false,
      default: undefined,
      type: String as PropType<string | undefined>,
    },
  },
  emits: {
    done: (val: boolean) => typeof val === 'boolean',
  },
  setup(props, { emit }) {
    const store = useEventStore();
    const startDate = computed(() => {
      const d = date.buildDate({ milliseconds: 0, seconds: 0, minutes: 0, hours: 0 });
      if (!props.date || !date.isValid(props.date)) return d;
      const split = props.date.split('-');
      return date.adjustDate(d, {
        year: parseInt(split[0]),
        month: parseInt(split[1]),
        date: parseInt(split[2]),
      });
    });

    const templates = computed(() => store.templates);
    const template = ref<FG.Event | undefined>(undefined);
    const event = ref<EditableEvent>(props.modelValue || emptyEvent(startDate.value));
    const eventtypes = computed(() => store.eventTypes);
    const recurrent = ref(false);
    const recurrenceRule = ref<FG.RecurrenceRule>({ frequency: 'daily', interval: 1 });

    onBeforeMount(() => {
      void store.getEventTypes();
      void store.getJobTypes();
      void store.getTemplates();
    });

    function addJob() {
      event.value.jobs.push(emptyJob());
    }

    function removeJob(index: number) {
      event.value.jobs.splice(index, 1);
    }

    function fromTemplate(tpl: FG.Event) {
      template.value = tpl;
      event.value = Object.assign({}, tpl);
    }

    async function save(template = false) {
      if (!event.value.is_template && template) event.value.id = NaN;

      event.value.is_template = template;
      try {
        if (event.value?.id !== undefined) {
          //fix
        }
        await store.addEvent(event.value);

        if (props.modelValue === undefined && recurrent.value && !event.value.is_template) {
          let count = 0;
          const options: ModifyDateOptions = {};
          switch (recurrenceRule.value.frequency) {
            case 'daily':
              options['days'] = 1 * recurrenceRule.value.interval;
              break;
            case 'weekly':
              options['days'] = 7 * recurrenceRule.value.interval;
              break;
            case 'monthly':
              options['months'] = 1 * recurrenceRule.value.interval;
              break;
          }
          while (true) {
            event.value.start = date.addToDate(event.value.start, options);
            if (event.value.end) event.value.end = date.addToDate(event.value.end, options);
            event.value.jobs.forEach((job) => {
              job.start = date.addToDate(job.start, options);
              if (job.end) job.end = date.addToDate(job.end, options);
            });
            count++;
            if (
              count <= 120 &&
              (!recurrenceRule.value.count || count <= recurrenceRule.value.count) &&
              (!recurrenceRule.value.until || event.value.start < recurrenceRule.value.until)
            )
              await store.addEvent(event.value);
            else break;
          }
        }
        reset();
        emit('done', true);
      } catch (error) {
        console.error(error);
      }
    }

    async function removeTemplate() {
      if (template.value !== undefined) {
        await store.removeEvent(template.value.id);
        template.value = undefined;
      }
    }

    function reset() {
      event.value = Object.assign({}, props.modelValue || emptyEvent());
      template.value = undefined;
    }

    const afterStart = (d: Date) =>
      !d || event.value.start <= d || 'Das Veranstaltungsende muss vor dem Beginn liegen';

    return {
      addJob,
      afterStart,
      event,
      eventtypes,
      fromTemplate,
      notEmpty,
      recurrenceRule,
      recurrent,
      removeJob,
      removeTemplate,
      reset,
      save,
      template,
      templates,
    };
  },
});
</script>

<style></style>
