/* FichothequeLib_Tools - Copyright (c) 2012-2023 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 net.fichotheque.tools.format;

import java.util.ArrayList;
import java.util.List;
import net.mapeadores.util.instruction.InstructionResolver;
import net.mapeadores.util.instruction.InstructionResolverProvider;


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

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

    public MultiInstructionResolverProviderBuilder() {
    }

    public void addFormatterFactoryProvider(InstructionResolverProvider instructionResolverProvider) {
        if (instructionResolverProvider instanceof MultiInstructionResolverProvider) {
            InstructionResolverProvider[] array = ((MultiInstructionResolverProvider) instructionResolverProvider).array;
            int length = array.length;
            for (int i = 0; i < length; i++) {
                providerList.add(array[i]);
            }
        } else {
            providerList.add(instructionResolverProvider);
        }
    }

    public InstructionResolverProvider toFormatterFactoryProvider() {
        int size = providerList.size();
        return new MultiInstructionResolverProvider(providerList.toArray(new InstructionResolverProvider[size]));
    }


    private static class MultiInstructionResolverProvider implements InstructionResolverProvider {

        private InstructionResolverProvider[] array;

        private MultiInstructionResolverProvider(InstructionResolverProvider[] array) {
            this.array = array;
        }

        @Override
        public InstructionResolver getInstructionResolver(Class destinationClass, Object optionObject) {
            int length = array.length;
            for (int i = 0; i < length; i++) {
                InstructionResolver resolver = array[i].getInstructionResolver(destinationClass, optionObject);
                if (resolver != null) {
                    return resolver;
                }
            }
            return null;
        }

    }

}
