/* BdfServer - Copyright (c) 2012-2020 Vincent Calame - Exemole
 * Logiciel libre donné sous triple licence :
 * 1) selon les termes de la CeCILL V2
 * 2) selon les termes de l’EUPL V.1.1
 * 3) selon les termes de la GNU GPLv3
 * Voir le fichier licences.txt
 */


package fr.exemole.bdfserver.tools.providers;

import fr.exemole.bdfserver.api.BdfServer;
import fr.exemole.bdfserver.api.menu.MenuGroup;
import fr.exemole.bdfserver.api.providers.MenuLinkProvider;
import fr.exemole.bdfserver.api.users.BdfUser;
import java.util.ArrayList;
import java.util.List;


/**
 *
 * @author Vincent Calame
 */
public class MultiMenuLinkProviderBuilder {

    private final List<MenuLinkProvider> providerList = new ArrayList<MenuLinkProvider>();

    public MultiMenuLinkProviderBuilder() {
    }

    public void addMenuLinkProvider(MenuLinkProvider menuLinkProvider) {
        if (menuLinkProvider instanceof MultiMenuLinkProvider) {
            MenuLinkProvider[] array = ((MultiMenuLinkProvider) menuLinkProvider).array;
            int length = array.length;
            for (int i = 0; i < length; i++) {
                providerList.add(array[i]);
            }
        } else {
            providerList.add(menuLinkProvider);
        }
    }

    public MenuLinkProvider toMenuLinkProvider() {
        int size = providerList.size();
        return new MultiMenuLinkProvider(providerList.toArray(new MenuLinkProvider[size]));
    }


    private static class MultiMenuLinkProvider implements MenuLinkProvider {

        private final MenuLinkProvider[] array;

        private MultiMenuLinkProvider(MenuLinkProvider[] array) {
            this.array = array;
        }

        @Override
        public MenuGroup[] getMenuGroupArray(BdfServer bdfServer, BdfUser bdfUser, Object menuObject) {
            List<MenuGroup> result = new ArrayList<MenuGroup>();
            int length = array.length;
            for (int i = 0; i < length; i++) {
                MenuGroup[] mlgArray = array[i].getMenuGroupArray(bdfServer, bdfUser, menuObject);
                if (mlgArray != null) {
                    int ln2 = mlgArray.length;
                    for (int j = 0; j < ln2; j++) {
                        result.add(mlgArray[j]);
                    }
                }
            }
            int size = result.size();
            if (size == 0) {
                return new MenuGroup[0];
            } else {
                return result.toArray(new MenuGroup[size]);
            }
        }

    }

}
