<template>
  <DialogFrame
    ref="dialog"
    :header-title="newEvent ? $t('addNewEvent') : $t('edit') + ' ' + localEvent.name"
    :height="250"
    :width="500"
  >
    <q-form ref="form">
      <div class="row justify-center q-gutter-md">
        <q-input
          class="q-ml-md col-5 required"
          :label="$t('eventName')"
          filled
          :rules="[(val) => !!val || $t('eventNameIsRequired')]"
          v-model="localEvent.name"
          autofocus
          @keyup.enter="save"
        ></q-input>
      </div>
    </q-form>
    <div class="row justify-center">
      <q-btn class="q-ma-md" color="primary" no-caps @click="save">{{ $t('save') }}</q-btn>
    </div>
  </DialogFrame>
</template>

<script setup lang="ts">
import DialogFrame from 'src/vueLib/dialog/DialogFrame.vue';
import { ref } from 'vue';
import { appApi } from 'src/boot/axios';
import type { Event } from 'src/vueLib/models/event';
import { useNotify } from 'src/vueLib/general/useNotify';

const { NotifyResponse } = useNotify();
const dialog = ref();
const form = ref();
const newEvent = ref(false);
const localEvent = ref<Event>({
  id: 0,
  name: '',
  attendees: [],
});

const emit = defineEmits(['update']);

function open(Event: Event | null) {
  if (Event === undefined) {
    return;
  }

  if (Event !== null) {
    localEvent.value = { ...Event };
    newEvent.value = Event.id === 0;
  } else {
    localEvent.value = {
      id: 0,
      name: '',
      attendees: [],
    };
    newEvent.value = true;
  }

  dialog.value?.open();
}

async function save() {
  const valid = await form.value.validate();

  if (!valid) return;

  let query = 'events/edit';
  let payload = JSON.stringify([localEvent.value]);
  if (newEvent.value) {
    query = 'events/add?name=' + localEvent.value.name;
    payload = JSON.stringify(localEvent.value);
  }

  appApi
    .post(query, payload)
    .then((resp) => {
      emit('update', resp.data.data);
      dialog.value.close();
    })
    .catch((err) => NotifyResponse(err, 'error'));
}

defineExpose({ open });
</script>

<style>
.required .q-field__label::after {
  content: ' *';
  color: red;
}
</style>
