/* BdfServer - Copyright (c) 2013-2015 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.StreamProducerProvider;
import java.util.ArrayList;
import java.util.List;
import net.mapeadores.util.io.StreamProducer;
import net.mapeadores.util.logging.ErrorMessageException;


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

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

    public MultiStreamProducerProviderBuilder() {
    }

    public void addStreamProducerProvider(StreamProducerProvider streamProducerProvider) {
        if (streamProducerProvider instanceof MultiStreamProducerProvider) {
            StreamProducerProvider[] array = ((MultiStreamProducerProvider) streamProducerProvider).array;
            int length = array.length;
            for (int i = 0; i < length; i++) {
                providerList.add(array[i]);
            }
        } else {
            providerList.add(streamProducerProvider);
        }
    }

    public StreamProducerProvider toStreamProducerProvider() {
        int size = providerList.size();
        return new MultiStreamProducerProvider(providerList.toArray(new StreamProducerProvider[size]));
    }


    private static class MultiStreamProducerProvider implements StreamProducerProvider {

        private StreamProducerProvider[] array;

        private MultiStreamProducerProvider(StreamProducerProvider[] array) {
            this.array = array;
        }

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

    }

}
