<template>
  <q-card>
    <q-form ref="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:modelValue="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"
        />
        <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.template_id === undefined && 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-card-section class="row justify-around" align="around">
          <div class="text-h6 text-center col-6">Schichten</div>
          <div class="col-6 text-center">
            <q-btn color="primary" label="Schicht hinzufügen" @click="addJob()" />
          </div>
        </q-card-section>
        <template v-for="(job, index) in event.jobs" :key="index">
          <job
            v-model="event.jobs[index]"
            :can-delete="jobDeleteDisabled"
            @remove-job="removeJob(index)"
          />
        </template>
      </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 { computed, defineComponent, PropType, ref, onBeforeMount } from 'vue';
import { date, ModifyDateOptions, QForm } from 'quasar';
import { useScheduleStore } from '../../store';
import { EditableEvent, emptyEvent, emptyJob } from '../../store/models';
import { notEmpty } from 'src/utils/validators';
import IsoDateInput from 'src/components/utils/IsoDateInput.vue';
import Job from './Job.vue';
import RecurrenceRule from './RecurrenceRule.vue';

export default defineComponent({
  name: 'EditEvent',
  components: { IsoDateInput, Job, RecurrenceRule },
  props: {
    modelValue: {
      required: false,
      default: () => undefined,
      type: Object as PropType<FG.Event | undefined>,
    },
  },
  emits: {
    done: (val: boolean) => typeof val === 'boolean',
  },
  setup(props, { emit }) {
    const store = useScheduleStore();

    const event = ref<EditableEvent>(props.modelValue || Object.assign({}, emptyEvent));
    const eventtypes = computed(() => store.eventTypes);
    const form = ref<QForm>();
    const jobDeleteDisabled = computed(() => event.value.jobs.length < 2);
    const recurrent = ref(false);
    const recurrenceRule = ref<FG.RecurrenceRule>({ frequency: 'daily', interval: 1 });
    const templates = computed(() => store.templates);
    const template = ref<FG.Event>();

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

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

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

    function fromTemplate(tpl: FG.Event) {
      const today = new Date();
      template.value = tpl;
      event.value = Object.assign({}, tpl);
      event.value.start = new Date(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate());
      const diff = event.value.start.getTime() - tpl.start.getTime();
      console.log(event.value);
      console.log(diff);
      if (event.value.end) event.value.end = new Date(event.value.end.getTime() + diff);

      event.value.jobs.forEach((job) => {
        job.start.setTime(job.start.getTime() + diff);
        if (job.end) job.end.setTime(job.end.getTime() + diff);
      });
    }

    async function save(template = false) {
      if (!(await form.value?.validate())) return;
      event.value.is_template = template;
      try {
        // Casting is save as .validate() ensures that type property is set!
        await store.addEvent(<FG.Event>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)
            )
              void store.addEvent(<FG.Event>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;
    }

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

<style></style>
