<template>
  <main class="d-flex align-center data-timing-range">
    <div class="d-flex align-center" style="max-height: 100%">
      <span class="label pl-2 mr-2 font-weight-bold on-neutral">
        {{ $t('period_choose') }}
      </span>

      <UiDateRangePicker
          :model-value="datesRange"
          :max-height="28"
          @update:model-value="updateDateTimeRange"
      />
    </div>
  </main>
</template>

<script setup lang="ts">
import type {Ref} from "@vue/reactivity";
import {useAccessProfileStore} from "~/stores/accessProfile";
import {useFormStore} from "~/stores/form";
import {useEntityManager} from "~/composables/data/useEntityManager";
import Access from "~/models/Access/Access";
import DateUtils from "~/services/utils/dateUtils";
import {usePageStore} from "~/stores/page";
import {useRefreshProfile} from "~/composables/data/useRefreshProfile";

const { setDirty } = useFormStore()
const accessProfileStore = useAccessProfileStore()
const { em } = useEntityManager()
const pageStore = usePageStore()
const { refreshProfile } = useRefreshProfile()

const start = accessProfileStore.historical.dateStart
const end = accessProfileStore.historical.dateEnd

const datesRange: Ref<Array<Date> | null> = ref((start && end) ? [new Date(start), new Date(end)] : null)

const updateDateTimeRange = async (dates: Array<Date>): Promise<any> => {

  const accessId = accessProfileStore.currentAccessId

  datesRange.value = dates

  if (datesRange.value !== null && datesRange.value[0] !== null && datesRange.value[1] !== null) {
    accessProfileStore.setHistoricalRange(
        DateUtils.formatIsoShortDate(datesRange.value[0]),
        DateUtils.formatIsoShortDate(datesRange.value[1])
    )
  } else {
    accessProfileStore.setHistorical(false, true, false)
  }
  setDirty(false)
  pageStore.loading = true

  await em.patch(Access, accessId, {'historical': accessProfileStore.historical})
  if (process.server) {
      // Force profile refresh server side to avoid a bug where server and client stores diverge on profile refresh
    await refreshProfile()
  }

  window.location.reload()
}
</script>

<style scoped lang="scss">
.label {
  min-width: 150px;
}
</style>
