<template>
  <q-page padding>
    <q-card>
      <q-form @submit="save" @reset="reset">
        <q-card-section class="fit row justify-start content-center items-center">
          <q-input
            class="col-xs-12 col-sm-6 q-pa-sm"
            label="Veranstaltungsname"
            v-model="eventname"
            filled
            :rules="[notEmpty]"
          />

          <q-input
            class="col-xs-12 col-sm-6 q-pa-sm"
            label="Beschreibung"
            type="textarea"
            v-model="event.description"
            filled
          />

          <IsoDateInput
            class="col-xs-12 col-sm-6 q-pa-sm"
            v-model="event.start"
            label="Veranstaltungstermin"
            :rules="[noValidDate, notEmpty]"
          />

          <q-select
            filled
            use-input
            label="Veranstaltungstyp"
            input-debounce="0"
            class="col-xs-12 col-sm-6 q-pa-sm"
            v-model="event.type"
            :options="eventtypes"
            option-label="name"
            option-value="name"
            map-options
            clearable
            :rules="[notEmpty]"
          />
        </q-card-section>
        <q-card-section>
          <q-btn color="primary" label="Schicht hinzufügen" @click="addJob()" />
        </q-card-section>

        <q-card-section v-for="job in event.jobs" v-bind:key="job.id">
          <q-card class="q-my-auto">
            <q-card-section class="fit row justify-start content-center items-center">
              <IsoDateInput
                class="col-xs-12 col-sm-6 q-pa-sm"
                v-model="job.start"
                label="Beginn"
                type="time"
                :rules="[noValidDate, notEmpty]"
              />
              <IsoDateInput
                class="col-xs-12 col-sm-6 q-pa-sm"
                v-model="job.end"
                label="Ende"
                type="time"
                :rules="[noValidDate, notEmpty]"
              />
              <q-input
                class="col-xs-12 col-sm-6 q-pa-sm"
                label="Beschreibung"
                type="textarea"
                v-model="job.description"
                filled
                :rules="[notEmpty]"
              />
              <q-select
                filled
                use-input
                label="Dienstart"
                input-debounce="0"
                class="col-xs-12 col-sm-6 q-pa-sm"
                v-model="job.type"
                :options="jobtypes"
                option-label="name"
                option-value="name"
                map-options
                clearable
                :rules="[notEmpty]"
              />
              <q-input label="Dienstanzahl" type="number" v-model="job.required_services" filled />
              <q-btn label="Schicht löschen" color="negative" @click="removeJob(job.id)" />
            </q-card-section>
          </q-card>
        </q-card-section>
        <q-card-actions align="right">
          <q-btn label="Reset" type="reset" />
          <q-btn color="primary" type="submit" label="Speichern" />
        </q-card-actions>
      </q-form>
    </q-card>
  </q-page>
</template>

<script lang="ts">
import { defineComponent, ref, onBeforeMount, computed } from '@vue/composition-api';
import IsoDateInput from 'src/components/utils/IsoDateInput.vue';
import { Store } from 'vuex';
import { StateInterface } from 'src/store';
import { ScheduleInterface } from '../../store/schedule';
import { date } from 'quasar';
// import { emit } from 'process';
export default defineComponent({
  name: 'CreateEvent',
  components: { IsoDateInput },
  setup(_, { root }) {
    const store = <Store<StateInterface>>root.$store;
    const state = <ScheduleInterface>store.state.schedule;
    const eventname = ref('');
    const eventdescription = ref('');
    const eventdate = ref<Date>();
    // const eventtype = ref<FG.EventType | null>('');
    const eventtypes = computed(() => state.eventTypes);
    const jobtypes = computed(() => state.jobTypes);
    let jobnum = 1;
    const newJob: FG.Job = {
      id: jobnum,
      start: new Date(),
      end: new Date(),
      comment: '',
      type: { id: NaN, name: '' },
      services: [],
      required_services: 2
    };
    // interface EventTypeToPost {
    //   name: string;
    // }
    // interface EventToPost {
    //   id: number;
    //   start: Date;
    //   description?: string;
    //   type: EventTypeToPost;
    //   jobs: Array<FG.Job>;
    // }
    const event = ref<FG.Event>({
      id: NaN,
      start: new Date(),
      description: '',
      type: { id: NaN, name: '' },
      jobs: [newJob]
    });

    const jobs = ref<FG.Job[]>([newJob]);

    onBeforeMount(() => {
      void store.dispatch('schedule/getEventTypes');
      void store.dispatch('schedule/getJobTypes');
    });
    function addJob() {
      console.log('Jobs: ', jobs);
      event.value.jobs.unshift(newJob);
      jobnum++;
    }

    function removeJob(id: number) {
      let jobtoremove = event.value.jobs.findIndex(job => job.id == id);
      if (jobtoremove != undefined) {
        jobs.value.splice(jobtoremove, 1);
        event.value.jobs.splice(jobtoremove, 1);
      }
    }
    function save() {
      // console.log('Eventtype:', eventtype);
      console.log('Event:', event);
      store.dispatch('schedule/addEvent', event.value).catch(error => {
        console.warn(error);
      });
    }

    function reset() {
      let nothing = 2;
      nothing++;
      nothing = 3;
    }
    function notEmpty(val: string) {
      return !!val || 'Feld darf nicht leer sein!';
    }
    function noValidDate(val: string) {
      return !!date.isValid(val) || 'Datum/Zeit muss gesetzt sein!';
    }
    return {
      eventname,
      eventdescription,
      eventdate,
      jobs,
      addJob,
      eventtypes,
      removeJob,
      jobtypes,
      notEmpty,
      noValidDate,
      save,
      reset,
      event
    };
  }
});
</script>

<style scoped></style>
