<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-card-section class="fit">
            <div class="text-h6">Veranstaltung erstellen</div>
          </q-card-section>
          <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]"
          />
          <IsoDateInput
            class="col-xs-12 col-sm-6 q-pa-sm"
            v-model="event.start"
            label="Veranstaltungsbeginn"
            :rules="[noValidDate, notEmpty]"
          />
        </q-card-section>
        <q-card-section class="fit justify-start content-center items-center">
          <q-input
            class="col-xs-12 col-sm-6 q-pa-sm"
            label="Beschreibung"
            type="textarea"
            v-model="event.description"
            filled
          />
        </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, index) in event.jobs" v-bind:key="index">
          <q-card class="q-my-auto">
            <job
              :job="job"
              :jobCanDelete="jobDeleteDisabled"
              @set-start="setStart"
              @set-required="setRequired"
              @set-end="setEnd"
              @set-comment="setComment"
              @set-job-type="setJobType"
              @remove-job="removeJob(index)"
            />
          </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 Job from './Job.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, Job },
  setup(_, { root }) {
    const store = <Store<StateInterface>>root.$store;
    const state = <ScheduleInterface>store.state.schedule;
    const eventtypes = computed(() => state.eventTypes);
    const jobDeleteDisabled = computed(() => event.value.jobs.length < 2);

    const newJob = ref<FG.Job>(({
      id: NaN,
      start: undefined,
      end: undefined,
      comment: '',
      services: [],
      required_services: 2
    } as unknown) as FG.Job);

    const event = ref<FG.Event>({
      id: NaN,
      start: new Date(),
      description: '',
      jobs: [Object.assign({}, newJob.value)]
    } as FG.Event);

    onBeforeMount(() => {
      void store.dispatch('schedule/getEventTypes');
      void store.dispatch('schedule/getJobTypes');
    });

    function setStart(data: { job: FG.Job; value: Date }) {
      data.job.start = data.value;
    }

    function setEnd(data: { job: FG.Job; value: Date }) {
      data.job.end = data.value;
    }

    function setComment(data: { job: FG.Job; value: string }) {
      data.job.comment = data.value;
    }

    function setJobType(data: { job: FG.Job; value: FG.JobType }) {
      data.job.type = data.value;
    }

    function setRequired(data: { job: FG.Job; value: number }) {
      data.job.required_services = data.value;
    }

    function addJob() {
      const addJob = Object.assign({}, newJob.value);
      event.value.jobs.unshift(addJob);
    }

    //function removeJob(id: number) {
    //  let jobtoremove = event.value.jobs.findIndex(job => job.id == id);
    //  if (jobtoremove != undefined) {
    //    event.value.jobs.splice(jobtoremove, 1);
    //  }
    //}

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

    function save() {
      console.log('Event:', event);
      store.dispatch('schedule/addEvent', event.value).catch(error => {
        console.warn(error);
      });
    }

    function reset() {
      event.value.id = NaN;
      event.value.start = new Date();
      event.value.description = '';
      event.value.type = {id: -1, name: ''};
      event.value.jobs = [Object.assign({}, newJob.value)];
    }
    function notEmpty(val: string) {
      return !!val || 'Feld darf nicht leer sein!';
    }
    function noValidDate(val: string) {
      return !!date.isValid(val) || 'Datum/Zeit muss gesetzt sein!';
    }

    function isAfterDate(val: Date) {
      // return event.value.jobsstart.getTime() > val.getTime() || 'Ende muss hinter dem Start liegen';
    }
    return {
      jobDeleteDisabled,
      addJob,
      eventtypes,
      removeJob,
      notEmpty,
      noValidDate,
      save,
      reset,
      event,
      isAfterDate,
      setStart,
      setEnd,
      setComment,
      setJobType,
      setRequired
    };
  }
});
</script>

<style scoped></style>
