<template>
  <section class="journal-timetables">
    <JournalHeader />

    <div class="journal_wrapper">
      <div class="journal_top-bar">
        <JournalOptions
          @onOptionsReset="resetOptions"
          @onRefreshData="fetchHistoryData"
          :sorter-option-ids="['timetableId', 'beginDate', 'routeDistance', 'allStopsCount']"
          :filters="journalTimetableFilters"
          :currentOptionsActive="currentOptionsActive"
          :data-status="dataStatus"
          optionsType="timetables"
        />

        <JournalStats :chosen-player-id="chosenPlayerId" />
      </div>

      <div class="journal_refreshed-date">
        {{ $t('journal.data-refreshed-at') }}:
        {{ dataRefreshedAt?.toLocaleString($i18n.locale) ?? '---' }}
      </div>

      <div class="list_wrapper" @scroll="handleScroll">
        <JournalTimetablesList
          :timetableHistory="timetableHistory"
          :addHistoryData="addHistoryData"
          :dataStatus="dataStatus"
          :scrollDataLoaded="scrollDataLoaded"
          :scrollNoMoreData="scrollNoMoreData"
          :extraInfoIndexes="extraInfoIndexes"
          @toggleExtraInfo="toggleExtraInfo"
        />
      </div>
    </div>
  </section>
</template>

<script lang="ts">
import { defineComponent, provide, reactive, Ref, ref } from 'vue';

import dateMixin from '../mixins/dateMixin';
import routerMixin from '../mixins/routerMixin';

import JournalOptions from '../components/JournalView/JournalOptions.vue';
import JournalStats from '../components/JournalView/JournalStats.vue';
import JournalHeader from '../components/JournalView/JournalHeader.vue';

import { useMainStore } from '../store/mainStore';

import { LocationQuery } from 'vue-router';

import JournalTimetablesList from '../components/JournalView/JournalTimetables/JournalTimetablesList.vue';
import { Journal } from '../components/JournalView/typings';
import { Status } from '../typings/common';
import { API } from '../typings/api';
import { useApiStore } from '../store/apiStore';

export const journalTimetableFilters: Journal.TimetableFilter[] = [
  {
    id: Journal.TimetableFilterId.ALL_STATUSES,
    filterSection: Journal.FilterSection.TIMETABLE_STATUS,
    isActive: true,
    default: true
  },

  {
    id: Journal.TimetableFilterId.ACTIVE,
    filterSection: Journal.FilterSection.TIMETABLE_STATUS,
    isActive: false,
    default: false
  },

  {
    id: Journal.TimetableFilterId.FULFILLED,
    filterSection: Journal.FilterSection.TIMETABLE_STATUS,
    isActive: false,
    default: false
  },

  {
    id: Journal.TimetableFilterId.ABANDONED,
    filterSection: Journal.FilterSection.TIMETABLE_STATUS,
    isActive: false,
    default: false
  },

  {
    id: Journal.TimetableFilterId.ALL_SPECIALS,
    filterSection: Journal.FilterSection.SPECIAL,
    isActive: true,
    default: true
  },

  {
    id: Journal.TimetableFilterId.TWR,
    filterSection: Journal.FilterSection.SPECIAL,
    isActive: false,
    default: false
  },

  {
    id: Journal.TimetableFilterId.SKR,
    filterSection: Journal.FilterSection.SPECIAL,
    isActive: false,
    default: false
  },
  {
    id: Journal.TimetableFilterId.TN,
    filterSection: Journal.FilterSection.SPECIAL,
    isActive: false,
    default: false
  },
  {
    id: Journal.TimetableFilterId.PN,
    filterSection: Journal.FilterSection.SPECIAL,
    isActive: false,
    default: false
  }
];

export default defineComponent({
  components: {
    JournalOptions,
    JournalStats,
    JournalHeader,
    JournalTimetablesList
  },
  mixins: [dateMixin, routerMixin],

  name: 'JournalTimetables',

  props: {
    timetableId: {
      type: String
    }
  },

  data: () => ({
    journalTimetableFilters,
    mainStore: useMainStore(),
    apiStore: useApiStore(),

    currentQueryParams: {} as API.TimetableHistory.QueryParams,
    dataRefreshedAt: null as Date | null,

    scrollDataLoaded: true,
    scrollNoMoreData: false,
    extraInfoIndexes: [] as number[],

    chosenPlayerId: -1,

    timetableHistory: [] as API.TimetableHistory.ResponseShort,

    dataStatus: Status.Data.Loading
  }),

  setup() {
    const sorterActive: Journal.TimetableSorter = reactive({ id: 'timetableId', dir: 'desc' });

    const initFilters: readonly Journal.TimetableFilter[] = JSON.parse(
      JSON.stringify(journalTimetableFilters)
    );

    const filterList: Journal.TimetableFilter[] = reactive(JSON.parse(JSON.stringify(initFilters)));

    const searchersValues = reactive({
      'search-train': '',
      'search-driver': '',
      'search-dispatcher': '',
      'search-includesScenery': '',
      'search-issuedFrom': '',
      'search-via': '',
      'search-terminatingAt': '',
      'search-headUnit': '',
      'search-date-from': '',
      'select-categoryCode': ''
    } as Journal.TimetableSearchType);

    const countFromIndex = ref(0);
    const countLimit = 15;

    provide('searchersValues', searchersValues);
    provide('sorterActive', sorterActive);
    provide('filterList', filterList);

    const scrollElement: Ref<HTMLElement | null> = ref(null);

    return {
      sorterActive,
      searchersValues,

      filterList,
      initFilters,

      countFromIndex,
      countLimit,

      scrollElement
    };
  },

  computed: {
    currentOptionsActive() {
      return Object.keys(this.currentQueryParams)
        .filter((k) => k != 'countFrom' && k != 'returnType')
        .some((k) => (this.currentQueryParams as any)[k] !== undefined);
    }
  },

  // Handle route updates for route-links
  beforeRouteUpdate(to) {
    this.handleQueries(to.query);
    this.fetchHistoryData();
  },

  activated() {
    this.handleQueries(this.$route.query);
    this.fetchHistoryData();
  },

  methods: {
    handleScroll(e: Event) {
      const listElement = e.target as HTMLElement;
      const scrollTop = listElement.scrollTop;
      const elementHeight = listElement.scrollHeight - listElement.offsetHeight;

      if (!this.scrollDataLoaded || this.scrollNoMoreData || this.dataStatus != Status.Data.Loaded)
        return;

      if (scrollTop > elementHeight * 0.85) this.addHistoryData();
    },

    handleQueries(query: LocationQuery) {
      this.setOptions(query as any);
    },

    async toggleExtraInfo(timetableDetails: API.TimetableHistory.Data | null) {
      if (!timetableDetails) return;

      const existingIdx = this.extraInfoIndexes.indexOf(timetableDetails.id);

      if (existingIdx == -1) {
        this.extraInfoIndexes.push(timetableDetails.id);

        const synchedTimetable = this.timetableHistory.find((t) => t.id == timetableDetails.id);

        if (synchedTimetable) {
          Object.assign(synchedTimetable, timetableDetails);
        }
      } else {
        this.extraInfoIndexes.splice(existingIdx, 1);
      }
    },

    setOptions(options: { [key: string]: string }) {
      Object.keys(this.searchersValues).forEach((v) => {
        this.searchersValues[v as Journal.TimetableSearchKey] = options[v] ?? '';
      });

      this.sorterActive.id =
        (options['sorter-active'] as Journal.TimetableSorterKey) ?? 'timetableId';

      this.filterList.forEach((f) => {
        f.isActive =
          options[f.filterSection] === f.id ||
          (options[f.filterSection] === undefined && f.default);
      });
    },

    resetOptions() {
      this.setOptions({});
    },

    async addHistoryData() {
      this.scrollDataLoaded = false;

      this.currentQueryParams['countFrom'] = this.timetableHistory.length;

      const responseData: API.TimetableHistory.Response = await this.apiStore.client.get(
        'api/getTimetables',
        this.currentQueryParams
      );

      if (!responseData) return;

      if (responseData.length == 0) {
        this.scrollNoMoreData = true;
        return;
      }

      this.timetableHistory.push(...responseData);
      this.scrollDataLoaded = true;
    },

    async fetchHistoryData() {
      this.extraInfoIndexes.length = 0;

      const queryParams: API.TimetableHistory.QueryParams = {};

      const driverName = this.searchersValues['search-driver'].trim() || undefined;
      const trainNo = this.searchersValues['search-train'].trim() || undefined;
      const authorName = this.searchersValues['search-dispatcher'].trim() || undefined;
      const dateFromString = this.searchersValues['search-date-from'].trim() || undefined;
      const includesScenery = this.searchersValues['search-includesScenery'].trim() || undefined;
      const issuedFrom = this.searchersValues['search-issuedFrom'].trim() || undefined;
      const via = this.searchersValues['search-via'].trim() || undefined;
      const terminatingAt = this.searchersValues['search-terminatingAt'].trim() || undefined;
      const categoryCode = this.searchersValues['select-categoryCode'].trim() || undefined;
      const headUnit = this.searchersValues['search-headUnit'].trim() || undefined;

      let dateFromISO: string | undefined = undefined;
      let dateToISO: string | undefined = undefined;

      if (dateFromString) {
        let dateFrom = new Date(dateFromString);
        dateFrom.setMinutes(dateFrom.getMinutes() + dateFrom.getTimezoneOffset());

        let dateTo = new Date(dateFrom);
        dateTo.setDate(dateTo.getDate() + 1);

        dateFromISO = dateFrom.toISOString();
        dateToISO = dateTo.toISOString();
      }

      this.filterList
        .filter((f) => f.isActive)
        .forEach((f) => {
          switch (f.id) {
            case Journal.TimetableFilterId.ABANDONED:
              queryParams['fulfilled'] = 0;
              queryParams['terminated'] = 1;
              break;

            case Journal.TimetableFilterId.ACTIVE:
              queryParams['fulfilled'] = undefined;
              queryParams['terminated'] = 0;
              break;

            case Journal.TimetableFilterId.FULFILLED:
              queryParams['terminated'] = undefined;
              queryParams['fulfilled'] = 1;
              break;

            case Journal.TimetableFilterId.ALL_STATUSES:
              queryParams['terminated'] = undefined;
              queryParams['fulfilled'] = undefined;
              break;

            case Journal.TimetableFilterId.ALL_SPECIALS:
              queryParams['twr'] = undefined;
              queryParams['skr'] = undefined;
              queryParams['pn'] = undefined;
              queryParams['tn'] = undefined;
              break;

            case Journal.TimetableFilterId.TWR:
              queryParams['twr'] = 1;
              break;

            case Journal.TimetableFilterId.SKR:
              queryParams['skr'] = 1;
              break;

            case Journal.TimetableFilterId.TN:
              queryParams['tn'] = 1;
              break;

            case Journal.TimetableFilterId.PN:
              queryParams['pn'] = 1;
              break;

            default:
              break;
          }
        });

      queryParams['driverName'] = driverName;
      queryParams[trainNo?.startsWith('#') ? 'timetableId' : 'trainNo'] = trainNo?.replace('#', '');
      queryParams['countFrom'] = undefined;
      queryParams['countLimit'] = undefined;

      queryParams['authorName'] = authorName;
      queryParams['dateFrom'] = dateFromISO;
      queryParams['dateTo'] = dateToISO;
      queryParams['includesScenery'] = includesScenery;
      queryParams['issuedFrom'] = issuedFrom;
      queryParams['terminatingAt'] = terminatingAt;
      queryParams['via'] = via;
      queryParams['categoryCode'] = categoryCode;
      queryParams['returnType'] = 'short';

      queryParams['issuedFrom'] = issuedFrom;
      queryParams['sortBy'] =
        this.sorterActive.id != 'timetableId' ? this.sorterActive.id : undefined;

      // Head unit params
      if (headUnit) {
        const [headUnitName, headUnitNumber] = headUnit.split('-');

        if (headUnitNumber && !isNaN(Number(headUnitNumber))) {
          queryParams['headUnitName'] = `${headUnitName}-${headUnitNumber}`;
        } else {
          queryParams['headUnitType'] = headUnitName;
        }
      }

      if (JSON.stringify(this.currentQueryParams) != JSON.stringify(queryParams))
        this.dataStatus = Status.Data.Loading;

      this.currentQueryParams = queryParams;

      try {
        const responseData: API.TimetableHistory.ResponseShort = await this.apiStore.client.get(
          'api/getTimetables',
          this.currentQueryParams
        );

        if (!responseData) {
          this.dataStatus = Status.Data.Error;
          this.chosenPlayerId = -1;
          return;
        }

        // Response data exists
        this.timetableHistory = responseData;

        this.chosenPlayerId =
          this.timetableHistory.length > 0 && this.searchersValues['search-driver'].trim() != ''
            ? this.timetableHistory[0].driverId
            : -1;

        this.dataStatus = Status.Data.Loaded;
        this.dataRefreshedAt = new Date();
      } catch (error) {
        this.dataStatus = Status.Data.Error;
        this.chosenPlayerId = -1;
      }

      this.scrollNoMoreData = false;
      this.scrollDataLoaded = true;
    }
  }
});
</script>

<style lang="scss" scoped>
@use '../styles/journal-section';
</style>
