/* BdfServer - Copyright (c) 2012-2022 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.OutputParameters;
import fr.exemole.bdfserver.api.providers.HtmlProducerProvider;
import java.util.ArrayList;
import java.util.List;
import net.mapeadores.util.html.HtmlProducer;
import net.mapeadores.util.logging.ErrorMessageException;


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

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

    public MultiHtmlProducerProviderBuilder() {
    }

    public void addHtmlProducerProvider(HtmlProducerProvider htmlProducerProvider) {
        if (htmlProducerProvider instanceof MultiHtmlProducerProvider) {
            HtmlProducerProvider[] array = ((MultiHtmlProducerProvider) htmlProducerProvider).array;
            int length = array.length;
            for (int i = 0; i < length; i++) {
                providerList.add(array[i]);
            }
        } else {
            providerList.add(htmlProducerProvider);
        }
    }

    public HtmlProducerProvider toHtmlProducerProvider() {
        int size = providerList.size();
        return new MultiHtmlProducerProvider(providerList.toArray(new HtmlProducerProvider[size]));
    }


    private static class MultiHtmlProducerProvider implements HtmlProducerProvider {

        private HtmlProducerProvider[] array;

        private MultiHtmlProducerProvider(HtmlProducerProvider[] array) {
            this.array = array;
        }

        @Override
        public HtmlProducer getHtmlProducer(OutputParameters parameters) throws ErrorMessageException {
            int length = array.length;
            for (int i = 0; i < length; i++) {
                HtmlProducer htmlProducer = array[i].getHtmlProducer(parameters);
                if (htmlProducer != null) {
                    return htmlProducer;
                }
            }
            return null;
        }

    }

}
