<script>
import { computed, shallowRef, watch } from 'vue';
import { useRoute } from 'vue-router';

import InputEvent from '../../../../../components/InputEvent.vue';
import { inject, keys as injectionKeys } from '../../../../../injection';
import { DateTime, cmp, time } from '@silane/datetime';


export default {
  name: 'PageMasterTimetableEventsIdEdit',
  components: { InputEvent },
  setup() {
    const route = useRoute();
    const notification = inject(injectionKeys.notification);
    const handleError = inject(injectionKeys.errorHandler).handleErrorAsync;
    const eventStore = inject(injectionKeys.eventStore);
    const generalTimetableScope = inject(injectionKeys.generalTimetableScope);

    const eventId = computed(() => route.params.id);
    const loading = shallowRef(false);
    const event = shallowRef(null);
    const eventInputInvalid = shallowRef(false);

    watch([
      eventId,
      generalTimetableScope.classroom, generalTimetableScope.dateRange,
    ], handleError(async () => {
      loading.value = true;
      const resp = await eventStore.query({ id: eventId.value });
      loading.value = false;
      const upEvent = resp.find(x => x.id === eventId.value) ?? null;
      if(!upEvent) {
        event.value = null;
        return;
      }
      if(!(cmp(DateTime.combine(
        generalTimetableScope.dateRange.value[0], time()
      ), upEvent.startTime) <= 0 && cmp(upEvent.endTime, DateTime.combine(
        generalTimetableScope.dateRange.value[1], time()
      )) <= 0)) {
        event.value = null;
        return;
      }
      event.value = {
        ...upEvent,
      };
    }), { immediate: true });

    const submit = handleError(async () => {
      if(eventInputInvalid.value) {
        notification.add('error', 'イベントの入力欄にエラーがあります');
        return;
      }

      await eventStore.mutate([{
        opcode: 'update_event', param: {
          id: eventId.value, type: event.value.type,
          resources: [...new Set([
            ...event.value.resources.map(x => x.id),
          ])],
          startTime: event.value.startTime, endTime: event.value.endTime,
          timeLabel: event.value.timeLabel?.id ?? null,
          color: event.value.color, memo: event.value.memo,
          ... event.value.type === 'lesson' ? {
            subject: event.value.subject, frame: event.value.frame,
          } : {},
        },
      }]);
      notification.add('info', 'イベントを更新しました');
    });

    return { loading, event, eventInputInvalid, submit };
  }
}
</script>

<template>
<h1>イベント編集</h1>
<p v-if="loading">読み込み中</p>
<template v-else>
  <form v-if="event" @submit.prevent="submit()">
    <InputEvent v-model="event" v-model:invalid="eventInputInvalid" />
    <button>編集確定</button>
  </form>
  <p v-else>イベントが見つかりません</p>
</template>
</template>
