<script lang="ts">
import { Date, DateTime, add, timedelta, time, cmp } from '@silane/datetime';
import { computed, ref, shallowRef, watch } from 'vue';

import InputResourceMultiSelect from '../../../components/InputResourceMultiSelect.vue';
import { inject, keys as injectionKeys } from '../../../injection';
import { datetimeRange } from '../../../common/utils.js';
import { getResourceDisplayText } from '../../../common/zkan-utils.js';
import type { Resource } from '../../../composables/resourcestore';


function dateToDateTimeRange(date: Date) {
  return {
    startTime: DateTime.combine(date, time()),
    endTime: DateTime.combine(add(date, timedelta({ days: 1 })), time()),
  };
}

export default {
  name: 'PageMasterTimetableTimelineprint',
  components: { InputResourceMultiSelect },
  setup() {
    const generalTimetableScope = inject(injectionKeys.generalTimetableScope);
    const resourceStore = inject(injectionKeys.resourceStore);
    const resourceHourStore = inject(injectionKeys.resourceHourStore);

    const resources = computed(() => resourceStore.resources.value.filter(
      x => !x.disabled && ['teacher', 'student'].includes(x.type)
    ));
    const dates = computed(() => [...datetimeRange(
      ...generalTimetableScope.dateRange.value, timedelta({ days: 1 })
    )]);

    const timelineMode = shallowRef<'' | 'date' | 'resource'>('');
    const selectedResources = shallowRef<Resource[]>([]);
    const selectedDates = ref<Date[]>([]);

    const datesClassroomOpen = shallowRef<Boolean[]>([]);
    watch(dates, async () => {
      datesClassroomOpen.value = await Promise.all(dates.value.map(
        async date => Boolean((await resourceHourStore.query({
          resource: generalTimetableScope.classroom.value,
          ...dateToDateTimeRange(date),
        })).length)
      ));
      selectedDates.value = dates.value.filter(
        (_, i) => datesClassroomOpen.value[i]
      );
    }, { immediate: true });
    const dateOptions = computed(() => dates.value.map((x, i) => ({
      date: x, classroomOpen: datesClassroomOpen.value[i] ?? false,
    })));

    const printingtimelineUrlSearchParams = computed(() => {
      if(timelineMode.value === 'date') {
        return {
          classroom: generalTimetableScope.classroom.value,
          mode: 'date-resource', resource: resources.value.filter(
            x => x.type === 'teacher'
          ).map(x => x.id).join(','),
          date: selectedDates.value.map(x => x.isoFormat()).join(','),
        };
      } else if(timelineMode.value === 'resource') {
        return {
          classroom: generalTimetableScope.classroom.value,
          mode: 'resource-date',
          resource: selectedResources.value.map(x => x.id).join(','),
          date: [...datetimeRange(
            ...generalTimetableScope.dateRange.value, timedelta({ days: 1 })
          )].map(x => x.isoFormat()).join(','),
        };
      } else return null;
    });

    return {
      URLSearchParams, cmp, add, timedelta, getResourceDisplayText,
      resources, dateOptions, timelineMode, selectedResources, selectedDates,
      printingtimelineUrlSearchParams,
    };
  },
}
</script>

<template>
<h1>時間割表印刷</h1>
<p>
  印刷用に複数の日付の日付表や複数のリソースのリソース表をまとめて表示できます。
  表示する時間割表の種類と、日付またはリソースのリストを選んで「印刷時間割表表示」または「印刷時間割表（外部送信用）表示」を押してください。
</p>

<fieldset>
  <legend>時間割表種類</legend>
  <label>
    <input type="radio" v-model="timelineMode" value="date" /> 日付表
  </label>
  <label>
    <input type="radio" v-model="timelineMode" value="resource" /> リソース表
  </label>
</fieldset>

<fieldset v-if="timelineMode === 'date'">
  <legend>日付</legend>
  <p>教室の可能時間が全くない（開室している時間がない）日付は選択できません。</p>
  <button type="button" @click="
    selectedDates = dateOptions.filter(x => x.classroomOpen).map(x => x.date)
  ">全選択</button>
  <button type="button" @click="selectedDates = []">全解除</button>
  <ol>
    <li v-for="{ date, classroomOpen } of dateOptions" :key="date.isoFormat()">
      <label>
        <input
          type="checkbox" v-model="selectedDates" :value="date"
          :disabled="!classroomOpen"
        />
        <date-time :value="date" />
      </label>
    </li>
  </ol>
</fieldset>

<fieldset v-if="timelineMode === 'resource'">
  <legend>リソース</legend>
  <label>
    リソース個別選択
    <input-resource-multi-select
      v-model="selectedResources" :options="resources"
    />
  </label>
  <button type="button" @click="
    selectedResources = resources.filter(x => x.type === 'teacher')
  ">全講師</button>
  <button type="button" @click="
    selectedResources = resources.filter(x => x.type === 'student')
  ">全生徒</button>
</fieldset>

<p>
  <router-link
    v-if="printingtimelineUrlSearchParams"
    :to="`/printingtimeline?${
      new URLSearchParams(printingtimelineUrlSearchParams)
    }`" target="_blank"
  >印刷時間割表表示</router-link>
  <span v-else class="disabledlink">印刷時間割表表示</span>
</p>
<p>
  <router-link
    v-if="printingtimelineUrlSearchParams"
    :to="`/printingtimeline?${new URLSearchParams({
      ...printingtimelineUrlSearchParams, hideconfidence: 'y',
    })}`" target="_blank"
  >印刷時間割表（外部送信用）表示</router-link>
  <span v-else class="disabledlink">印刷時間割表（外部送信用）表示</span>
</p>
</template>

<style scoped>
.disabledlink {
  color: lightgray;
  text-decoration: underline;
}
</style>
