<script lang="ts">
import { Date, DateTime } from '@silane/datetime';
import { computed, type PropType } from 'vue';

import DateAndResourceTimeTable from '../components/DateAndResourceTimeTable.vue';
import { inject, keys as injectionKeys } from '../injection';
import { kanaToRoman } from '../common/kana-roman.js';
import { getUniquePeopleNames } from '../common/zkan-utils.js';
import type { Resource } from '../composables/resourcestore';


export default {
  name: 'PagePrintingtimeline',
  components: { DateAndResourceTimeTable },
  props: {
    classroom: { type: String, required: true },
    mode: {
      type: String as PropType<'date-resource' | 'resource-date'>,
      required: true,
    },
    resource: { type: String, default: '' },
    date: { type: String, required: true },
    hideConfidence: { type: Boolean, default: false },
  },
  setup(props) {
    const resourceStore = inject(injectionKeys.resourceStore);
    const today = Date.today();

    const classroom = computed(() => resourceStore.resources.value.find(
      x => x.id === props.classroom
    ) ?? null);
    const dates = computed(() => {
      if(!props.date) return [];
      try {
        return props.date.split(',').map(x => Date.fromISOFormat(x));
      } catch {
        return [];
      }
    });
    const resources = computed(() => {
      return props.resource.split(',').map(
        x => resourceStore.resources.value.find(r => r.id === x)
      ).filter((x): x is Resource => Boolean(x));
    });

    const resourceDisplayTexts = computed(() => {
      const resources = resourceStore.resources.value.filter((x): x is Extract<
        Resource, { type: 'teacher' } | { type: 'student' }
      > => ['teacher', 'student'].includes(x.type));
      return new Map(getUniquePeopleNames(resources).map(
        (x, i) => [resources[i].id, x]
      ));
    });

    const titles = computed(() => {
      if(props.mode === 'resource-date') {
        return resources.value.map(r => {
          if(r.type === 'student') {
            return props.hideConfidence ? `${r.grade.label} ${
              kanaToRoman(r.lastNameKana)[0].toUpperCase()
            }. ${kanaToRoman(r.firstNameKana)[0].toUpperCase()}. 様` : `${
              r.grade.label
            } ${r.lastName} ${r.firstName} 様`;
          } else if(r.type === 'teacher') {
            return props.hideConfidence ? resourceDisplayTexts.value.get(
              r.id
            )! : `${r.lastName} ${r.firstName}`;
          } else return '';
        });
      } else if(props.mode === 'date-resource') {
        return dates.value.map(x => `${x.strftime('%Y/%m/%d')} (${[
          '月', '火', '水', '木', '金', '土', '日',
        ][x.weekday()]})`);
      } else {
        return [];
      }
    });

    return { today, classroom, dates, resources, titles };
  }
}
</script>

<template>
<template v-if="classroom && dates.length && resources.length">
  <template v-if="mode === 'date-resource'">
    <section
      v-for="date, dateIdx of dates" :key="date.isoFormat()" class="page"
    >
      <header class="header">
        <h1>{{ titles[dateIdx] }}</h1>
        <small><DateTime :value="today" :format="'%Y/%m/%d'" /></small>
      </header>
      <DateAndResourceTimeTable
        :classroom="classroom" mode="date"
        :dates="[date]" :resources="resources" class="printingtimetable"
        :hide-confidence="hideConfidence"
      />
    </section>
  </template>
  <template v-else-if="mode === 'resource-date'">
    <section
      v-for="resource, resourceIdx of resources" :key="resource.id" class="page"
    >
      <header class="header">
        <h1>{{ titles[resourceIdx] }}</h1>
        <small><DateTime :value="today" :format="'%Y/%m/%d'" /></small>
      </header>
      <DateAndResourceTimeTable
        :classroom="classroom" mode="resource"
        :dates="dates" :resources="[resource]" class="printingtimetable"
        :hide-confidence="hideConfidence"
      />
    </section>
  </template>
  <p v-else>不正なモード値です。</p>
</template>
<p v-if="!classroom">教室がみつかりません。</p>
<p v-if="!dates.length">日付が指定されていないか、形式が不正です。</p>
<p v-if="!resources.length">リソースがみつかりません。</p>
</template>

<style scoped>
@page {
  size: calc(297mm * 2) calc(210mm * 2);
  margin: 0;
  padding: 0;
}

.page {
  box-sizing: border-box;
  width: calc(297mm * 2);
  height: calc(210mm * 2);
  padding: 30px 30px;
  display: grid;
  grid-template-rows: auto 1fr;
  break-inside: avoid-page;
}
:nth-child(1 + n of .page) {
  break-before: page;
}

.header {
  display: grid;
  grid-template-columns: 1fr auto 1fr;
}
.header h1 {
  all: unset;
  grid-column: 2;
  font-size: 40px;
  margin: 1em 0;
}
.header small {
  grid-column: 3;
  text-align: right;
}

.printingtimetable:deep(.timetable-timeheader),
.printingtimetable:deep(.timetable-columnheader) {
  font-size: 15px;
}
.printingtimetable:deep(.timetable-event) {
  font-size: 15px;
}
</style>
