<template>
  <main class="d-flex flex-row align-center">
    <span v-show="mdAndUp" class="mr-2 font-weight-bold">{{ $t(label) }} : </span>

    <UiXeditableText
      class="activity-year-input bg-ot-light-grey"
      type="number"
      :data="currentActivityYear"
      @update="setActivityYear"
    >
      <template #xeditable.read="{inputValue}">
        <v-icon aria-hidden="false" size="small" class="text-ot-green mr-1" icon="fas fa-edit" />
        <strong class="text-ot-green">
          {{ inputValue }}
          <span v-if="yearPlusOne">
            / {{ parseInt(inputValue) + 1 }}
          </span>
        </strong>
      </template>
    </UiXeditableText>
  </main>
</template>

<script setup lang="ts">

import {useEntityManager} from "~/composables/data/useEntityManager";
import {useFormStore} from "~/stores/form";
import {useOrganizationProfileStore} from "~/stores/organizationProfile";
import {useAccessProfileStore} from "~/stores/accessProfile";
import Access from "~/models/Access/Access";
import {Ref, ref} from "@vue/reactivity";
import {useDisplay} from "vuetify";

const { em } = useEntityManager()
const accessProfileStore = useAccessProfileStore()
const organizationProfileStore = useOrganizationProfileStore()
const formStore = useFormStore()
const { mdAndUp } = useDisplay()

const currentActivityYear: Ref<number | null> = ref(accessProfileStore.activityYear)
const yearPlusOne: boolean = !organizationProfileStore.isManagerProduct
const label: string = organizationProfileStore.isSchool ? 'schooling_year' : organizationProfileStore.isArtist ? 'season_year' : 'cotisation_year'

/**
 * Persist a new activityYear
 * @param activityYear
 */
const setActivityYear = async (activityYear: number) => {
  if (!(1900 < activityYear) || !(activityYear <= 2100)) {
    throw new Error("Error: 'year' shall be a valid year")
  }
  if (accessProfileStore.id === null) {
    throw new Error("Error: invalide access id")
  }
  formStore.setDirty(false)

  const access = await em.fetch(Access, accessProfileStore.id)
  access.activityYear = activityYear
  await em.persist(Access, access)

  // Update the store
  // TODO: voir si mieux d'automatiser ces maj du profil, ou de les faire à la main au cas par cas?
  accessProfileStore.$patch({ activityYear: activityYear })

  window.location.reload()
}

</script>

<style lang="scss">
  .activity-year-input {
    width: 120px;
    max-height: 20px;

    .v-input {
      min-width: 70px;
    }

    input{
      font-size: 14px;
      width: 55px !important;
      padding: 0 !important;
      margin-top: 0 !important;
      min-height: 24px;
      height: 24px;
    }
  }
</style>
