import { Ability } from '@casl/ability'
import { NuxtConfig } from '@nuxt/types/config'
import * as _ from 'lodash'
import BaseMenu from '~/composables/layout/Menus/baseMenu'
import { AnyStore, ItemMenu, ItemsMenu, Menu } from '~/types/interfaces'

/**
 * @category composables/layout/Menus
 * @class MyFamilyMenu
 * Classe pour la construction du Menu Famille
 */
class MyFamilyMenu extends BaseMenu implements Menu {
  private $ability: Ability;
  private $store: AnyStore;

  /**
   * @constructor
   * Initialisation des services issues du context
   */
  constructor ($config: NuxtConfig, $ability: Ability, $store: AnyStore) {
    super($config)
    this.$ability = $ability
    this.$store = $store
  }

  /**
   * Construit le menu Header Changement d'utilisateur ou null si aucune page accessible
   * @return {ItemMenu | null}
   */
  getHeaderMenu (): ItemMenu | null {
    const children: ItemsMenu = []

    // Si Access des membres de la familles (enfants)
    _.each(this.$store.state.profile.access.familyAccesses, (access) => {
      const url = `/switch_user/${this.$store.state.profile.organization.id}/${this.$store.state.profile.access.id}/${access.id}`
      children.push(this.constructMenu(`${access.givenName} ${access.name}`, undefined, url, true))
    })

    // Si on est en compte swtich, on doit pouvoir retourner au compte d'origine
    if (this.$store.state.profile.access.originalAccess) {
      const originalAccess = this.$store.state.profile.access.originalAccess
      const url = `/switch_user/${originalAccess.organization.id}/${originalAccess.id}/exit`
      children.push(this.constructMenu(`${originalAccess.givenName} ${originalAccess.name}`, undefined, url, true))
    }

    return children.length > 0 ? this.constructMenu('familyAccesses', 'fa-users', undefined, undefined, children) : null
  }
}

export const getMyFamilyMenu = ($config: NuxtConfig, $ability: Ability, $store: AnyStore) => new MyFamilyMenu($config, $ability, $store).getHeaderMenu()
