<script>
import { ref } from 'vue';

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


export default {
  name: 'PageMasterConfigDatareduction',
  setup() {
    const handleError = inject(injectionKeys.errorHandler).handleErrorAsync;
    const notification = inject(injectionKeys.notification);
    const resourceStore = inject(injectionKeys.resourceStore);
    const resourceHourStore = inject(injectionKeys.resourceHourStore);
    const eventStore = inject(injectionKeys.eventStore);

    const removeOldDataDateBefore = ref(null);

    const removeOldData = handleError(async () => {
      if(!removeOldDataDateBefore.value) {
        return;
      }

      const datetimeBefore = DateTime.combine(
        removeOldDataDateBefore.value, time()
      );

      await resourceHourStore.mutate(resourceStore.resources.value.map(x => ({
        opcode: 'unfill', param: {
          resource: x.id, startTime: DateTime.min, endTime: datetimeBefore,
        }
      })));

      const oldEvents = await eventStore.query({
        startTime: DateTime.min, endTime: datetimeBefore,
      });
      const eventsToRemvoe = new Set(oldEvents.filter(
        x => cmp(x.endTime, datetimeBefore) <= 0
      ));
      const eventsAfter = new Set(
        oldEvents.filter(x => !eventsToRemvoe.has(x))
      );
      while(eventsAfter.size) {
        const event = /** @type {
          import('../../../composables/eventstore.ts').Event
        } */(eventsAfter.values().next().value);
        eventsAfter.delete(event);
        eventsToRemvoe.delete(event);
        if(event.eventChangeFrom?.fromEvent) {
          eventsAfter.add(event.eventChangeFrom.fromEvent);
        }
        if(event.eventChangeTo?.toEvent) {
          eventsAfter.add(event.eventChangeTo.toEvent);
        }
      }
      await eventStore.mutate([...eventsToRemvoe].map(x => ({
        opcode: 'remove_event', param: { id: x.id },
      })));

      notification.add('info', '削除しました。');
    });

    return { removeOldDataDateBefore, removeOldData };
  },
}
</script>

<template>
<h1>データ削減</h1>
<p>
  指定した日付より前のイベント、可能時間を全て削除します。
  ただし日付以後のイベントの振替元や振替先に指定されたイベントは削除されません。
</p>
<form @submit.prevent="removeOldData()">
  <label>
    日付 <input-date v-model="removeOldDataDateBefore" />
  </label>
  <button :disabled="!removeOldDataDateBefore">
    <date-time
      v-if="removeOldDataDateBefore" :value="removeOldDataDateBefore"
    /> より前のデータを削除
  </button>
</form>
</template>
