import { Ability } from '@casl/ability'
import { NuxtConfig } from '@nuxt/types/config'
import { AnyStore, ItemMenu, ItemsMenu, Menu } from '~/types/interfaces'
import { $organizationProfile } from '~/services/profile/organizationProfile'
import BaseMenu from '~/composables/layout/Menus/baseMenu'

/**
 * @category composables/layout/Menus
 * @class AccessMenu
 * Classe pour la construction du Menu Répertoire
 */
class AccessMenu extends BaseMenu implements Menu {
  private $ability: Ability;
  private readonly $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 Répertoire, ou null si aucune page accessible
   * @return {ItemMenu | null}
   */
  getMenu (): ItemMenu | null {
    const children: ItemsMenu = []

    if (this.$ability.can('display', 'accesses_page')) {
      const organization = $organizationProfile(this.$store)
      const to = organization.isSchool() ? '/students/list/' : '/adherent/list/'
      children.push(this.constructMenu('person', 'fa-user', to, true))
    }

    if (this.$ability.can('display', 'student_registration_page')) {
      children.push(this.constructMenu('family_view', 'fa-users', '/student_registration/new', true))
    }

    if (this.$ability.can('display', 'education_student_next_year_page')) {
      children.push(this.constructMenu('education_student_next_year', 'fa-list-alt', '/education_student_next_year/list/', true))
    }

    if (this.$ability.can('display', 'commissions_page')) {
      children.push(this.constructMenu('commissions', 'fa-street-view', '/commissions/list/', true))
    }

    if (this.$ability.can('display', 'network_children_page')) {
      children.push(this.constructMenu('network', 'fa-sitemap', 'networks/list/', true))
    }

    if (this.$ability.can('display', 'network_parents_page')) {
      children.push(this.constructMenu('my_network', 'fa-sitemap', '/network_artist_schools/list/', true))
    }

    if (children.length === 1) {
      return children[0]
    } else if (children.length > 0) {
      return this.constructMenu('address_book', 'fa-address-book', undefined, undefined, children)
    } else {
      return null
    }
  }
}

export const getAccessMenu = ($config: NuxtConfig, $ability: Ability, $store: AnyStore) => new AccessMenu($config, $ability, $store).getMenu()
