<template>
  <main>
    <v-menu
      bottom
      left
      transition="slide-y-transition"
      :close-on-content-click="false"
      min-width="500"
    >
      <template #activator="{ on, attrs }">
        <span
          v-bind="attrs"
          class="ot_green--text"
          v-on="on"
        >
          {{ $t('my_list') }}
        </span>
      </template>
      <v-list>
        <v-list-item>
          <v-list-item-title>
            <UiInputAutocomplete
              :label="$t('searchList')"
              :is-loading="isLoading"
              :items="items"
              :item-text="['label']"
              :return-object="true"
              @update="goOn"
            />
          </v-list-item-title>
        </v-list-item>
      </v-list>
    </v-menu>
  </main>
</template>

<script lang="ts">
import {
  computed, defineComponent, useContext, useFetch, ref, Ref, ComputedRef
} from '@nuxtjs/composition-api'
import { Collection } from '@vuex-orm/core'
import { QUERY_TYPE } from '~/types/enums'
import { PersonalizedList } from '~/models/Access/PersonalizedList'
import { repositoryHelper } from '~/services/store/repository'
import { AnyJson } from '~/types/interfaces'
import { $objectProperties } from '~/services/utils/objectProperties'
import VueI18n from "vue-i18n";

export default defineComponent({
  fetchOnServer: false,
  setup () {
    const { $dataProvider, $config } = useContext()
    const isLoading: Ref<boolean> = ref(true)
    const homeUrl:string = $config.baseURL_adminLegacy

    useFetch(async () => {
      await $dataProvider.invoke({
        type: QUERY_TYPE.MODEL,
        model: PersonalizedList
      })
      isLoading.value = false
    })

    const items:ComputedRef<Array<AnyJson>> = computed(() => {
      const lists = repositoryHelper.findCollectionFromModel(PersonalizedList, {'id':'desc'}) as Collection<PersonalizedList>

      let listsGroupByKeyMenu:Array<AnyJson> = groupListByKey(lists)

      listsGroupByKeyMenu = $objectProperties.sortObjectByKey(listsGroupByKeyMenu)

      return constructAutoCompleteItems(listsGroupByKeyMenu)
    })

    const goOn = (list:PersonalizedList) => {
      window.location.href = `${homeUrl}/${list.entity}/list/${list.id}`
    }

    return {
      items,
      isLoading,
      goOn
    }
  }
})

/**
   * On regroupe la list par clé afin de constituer les groups
   * @param lists
   * @param i18n
   */
function groupListByKey (lists:Collection<PersonalizedList>): Array<AnyJson> {
  const { app: { i18n } } = useContext()
  const listsGroupByKeyMenu:any = {}
  for (const list of lists) {
    const key = i18n.t(list.menuKey) as string
    listsGroupByKeyMenu[key] = listsGroupByKeyMenu[key] ?? []
    listsGroupByKeyMenu[key].push(list)
  }
  return listsGroupByKeyMenu
}

/**
   * On construit la list d'Item, constituée de Header et d'Item "sélectionnable"
   * @param listsGroupByKeyMenu
   */
function constructAutoCompleteItems (listsGroupByKeyMenu:Array<any>) {
  const items: any = []
  for (const key in listsGroupByKeyMenu) {
    items.push({ header: key })
    for (const item of listsGroupByKeyMenu[key]) {
      items.push(item)
    }
  }
  return items
}
</script>

<style scoped>

</style>
