import MainMenuBuilder from "~/services/layout/menuBuilder/mainMenuBuilder";
import {AccessProfile, LayoutState, organizationState} from "~/types/interfaces";
import WebsiteListMenuBuilder from "~/services/layout/menuBuilder/websiteListMenuBuilder";
import MyAccessesMenuBuilder from "~/services/layout/menuBuilder/myAccessesMenuBuilder";
import MyFamilyMenuBuilder from "~/services/layout/menuBuilder/myFamilyMenuBuilder";
import ConfigurationMenuBuilder from "~/services/layout/menuBuilder/configurationMenuBuilder";
import AccountMenuBuilder from "~/services/layout/menuBuilder/accountMenuBuilder";
import {RuntimeConfig} from "@nuxt/schema";
import {AnyAbility} from "@casl/ability";
import {MenuBuilder, MenuGroup} from "~/types/layout";

/**
 * Gestionnaire principal des menus de l'application
 */
export default class MenuComposer {

    // @ts-ignore TODO: mieux typer cette prop
    protected static readonly builders: Array<any> = [
        MainMenuBuilder,
        WebsiteListMenuBuilder,
        MyAccessesMenuBuilder,
        MyFamilyMenuBuilder,
        ConfigurationMenuBuilder,
        AccountMenuBuilder,
    ]

    /**
     * Construit l'ensemble des menus et les insère dans le store Layout
     *
     * @param runtimeConfig
     * @param ability
     * @param organizationProfile
     * @param accessProfile
     * @param layoutState
     */
    public static build(
        runtimeConfig: RuntimeConfig,
        ability: AnyAbility,
        organizationProfile: organizationState,
        accessProfile: AccessProfile,
        layoutState: LayoutState
    ) {
        for (const builderClass of MenuComposer.builders) {

            const builder: MenuBuilder = new builderClass(runtimeConfig, ability, organizationProfile, accessProfile)
            const menuName = builder.getMenuName()
            const menu = builder.build();

            if (!menu) {
                continue
            }

            // Store a ref to the menu in the store
            layoutState.menus[menuName] = menu

            // On enregistre l'état du menu dans le store de la page
            if ( ((menu as MenuGroup).children ?? []).length > 0 ) {
                layoutState.menusOpened[menuName] = false
            }
        }
    }
}
