<template>
  <v-row justify="center" align="center">
    <v-col cols="12" sm="8" md="8">

        <FormComponent>

          <v-expansion-panels v-model="panel" focusable>

            <ExpansionPanelComponent title="Informations générales">
              <InputComponent :query="accessesQuery" field="person.name" :rules="nameRule" />
              <InputComponent :query="accessesQuery" field="person.givenName" />
            </ExpansionPanelComponent>

            <ExpansionPanelComponent title="Activités">
              <DataTableComponent :repository="personActivitiesRepository" :uri="personActivitiesUri" :headers="personActivitiesHearders"></DataTableComponent>
            </ExpansionPanelComponent>

          </v-expansion-panels>

        </FormComponent>

    </v-col>
  </v-row>
</template>


<script lang="ts">
  import {defineComponent, useContext} from '@nuxtjs/composition-api'
  import {Access} from '@/models/Access/Access'
  import {Person} from '@/models/Person/Person'
  import {PersonActivity} from '@/models/Person/PersonActivity'

  export default defineComponent({
    setup() {
      const {store, route} = useContext();
      const panel = 0
      const accessesRepository = store.$repo(Access)
      const accessesQuery = accessesRepository.with('person')
      const personActivitiesRepository = store.$repo(PersonActivity)

      const personActivitiesUri = `${accessesRepository.getModel().$entity}/${route.value.params.id}/${personActivitiesRepository.getModel().$entity}`
      const personActivitiesHearders = [
        {
          text: 'Activité',
          align: 'start',
          sortable: false,
          value: 'complementSpeciality',
        },
        { text: 'Date de début',
          value: 'startDate'
        }
      ]

      const nameRule = [
        (nameValue:string) => (nameValue || '').length <= 128 || `A maximum of 128 characters is allowed`
      ]

      return {
        accessesQuery,
        personActivitiesRepository,
        personActivitiesUri,
        personActivitiesHearders,
        panel,
        nameRule
      }
    },

    async asyncData({store, $rest, params}){
      const repository = store.$repo(Access);
      const entity = repository.getModel().$entity;
      const access = await $rest.getItem(`/api/${entity}`, params.id)
      // const accesses = await accessesData()
      repository.insert(access);
    },

    async beforeRouteLeave (to, from, next) {
      const flushAccess =  await this.$store.$repo(Access).flush();
      const flushPerson =  await this.$store.$repo(Person).flush();
      const flushPersonActivity =  await this.$store.$repo(PersonActivity).flush();
      next();
    }
  })
</script>
