<script lang="ts">
import { ref, shallowRef } from 'vue';
import { DateTime, Time } from '@silane/datetime';

import InputEvent, {
  type ModelValuePropType as InputEventModelValuePropType,
} from '../../../../components/InputEvent.vue';
import { inject, keys as injectionKeys } from '../../../../injection';
import type { Resource } from '../../../../composables/resourcestore';
import { eventToEventInput } from '../../../../composables/eventstore';


export default {
  name: 'PageMasterTimetableEventsNew',
  components: { InputEvent },
  setup() {
    const notification = inject(injectionKeys.notification);
    const resourceStore = inject(injectionKeys.resourceStore);
    const eventStore = inject(injectionKeys.eventStore);
    const generalTimetableScope = inject(injectionKeys.generalTimetableScope);

    const event = shallowRef<InputEventModelValuePropType>({
      type: 'standard', resources: [resourceStore.resources.value.find(
        r => r.id === generalTimetableScope.classroom.value
      )].filter((x): x is Resource => x != null), startTime: DateTime.combine(
        generalTimetableScope.dateRange.value[0], new Time()
      ), endTime: DateTime.combine(
        generalTimetableScope.dateRange.value[0], new Time()
      ), timeLabel: null, color: '#FFFFFF', memo: '',
    });
    const eventInputInvalid = ref(false);

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

      await eventStore.mutate([{
        opcode: 'add_event', param: eventToEventInput(event.value),
      }]);
      notification.add('info', 'イベントを追加しました');
    }

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

<template>
<h1>イベント追加</h1>
<form @submit.prevent="submit()">
  <input-event v-model="event" v-model:invalid="eventInputInvalid" />
  <button>イベント追加</button>
</form>
</template>
