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

/**
 * @category composables/layout/Menus
 * @class WebsiteMenu
 * Classe pour la construction du Menu Sites internet
 */
class WebsiteMenu 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 Site internet ou null si aucune page accessible
   * @return {ItemMenu | null}
   */
  getMenu (): ItemMenu | null {
    if (!this.$store.state.profile.organization.website && this.$store.state.profile.access.isAdminAccess) {
      return this.constructMenu('advanced_modification', 'fa-globe-europe', this.getWebsite(this.$store.state.profile.organization) + '/typo3', false, undefined, true)
    }
    return null
  }

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

    children.push(this.constructMenu(this.$store.state.profile.organization.name, undefined, this.getWebsite(this.$store.state.profile.organization), false, undefined, true))

    _.each(this.$store.state.profile.organization.parents, (parent) => {
      if(parent.id != process.env.OPENTALENT_MANAGER_ID){
        children.push(this.constructMenu(parent.name, undefined, this.getWebsite(parent), false, undefined, true))
      }
    })

    return children.length > 0 ? this.constructMenu('website', 'fa-globe-europe', undefined, undefined, children) : null
  }

  getWebsite (organization: organizationState): string {
    return organization.website ? organization.website : this.$config.baseURL_typo3.replace('###subDomain###', organization.subDomain)
  }
}

export const getWebsiteMenu = ($config: NuxtConfig, $ability: Ability, $store: AnyStore) => new WebsiteMenu($config, $ability, $store)
