/* 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.instruction.BdfCommand;
import fr.exemole.bdfserver.api.instruction.BdfCommandParameters;
import fr.exemole.bdfserver.api.providers.BdfCommandProvider;
import java.util.ArrayList;
import java.util.List;


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

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

    public MultiBdfCommandProviderBuilder() {
    }

    public MultiBdfCommandProviderBuilder addBdfCommandProvider(BdfCommandProvider bdfCommandProvider) {
        if (bdfCommandProvider instanceof MultiBdfCommandProvider) {
            BdfCommandProvider[] array = ((MultiBdfCommandProvider) bdfCommandProvider).array;
            for (BdfCommandProvider provider : array) {
                providerList.add(provider);
            }
        } else {
            providerList.add(bdfCommandProvider);
        }
        return this;
    }

    public BdfCommandProvider toBdfCommandProvider() {
        return new MultiBdfCommandProvider(providerList.toArray(new BdfCommandProvider[providerList.size()]));
    }

    public static MultiBdfCommandProviderBuilder init() {
        return new MultiBdfCommandProviderBuilder();
    }


    private static class MultiBdfCommandProvider implements BdfCommandProvider {

        private final BdfCommandProvider[] array;

        private MultiBdfCommandProvider(BdfCommandProvider[] array) {
            this.array = array;
        }

        @Override
        public BdfCommand getBdfCommand(BdfCommandParameters parameters) {
            for (BdfCommandProvider provider : array) {
                BdfCommand bdfCommand = provider.getBdfCommand(parameters);
                if (bdfCommand != null) {
                    return bdfCommand;
                }
            }
            return null;
        }

    }

}
