/* BdfServer - Copyright (c) 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.externalsource;

import fr.exemole.bdfserver.api.externalsource.ExternalSourceType;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import net.mapeadores.util.localisation.Litteral;


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

    private final String name;
    private final Map<String, ExternalSourceType.Param> paramMap = new LinkedHashMap<String, ExternalSourceType.Param>();
    private Object l10nObject;


    public ExternalSourceTypeBuilder(String name) {
        if (name == null) {
            throw new IllegalArgumentException("name is null");
        }
        this.name = name;
    }

    public ExternalSourceTypeBuilder setL10nObject(Object l10nObject) {
        this.l10nObject = l10nObject;
        return this;
    }

    public ExternalSourceTypeBuilder addParam(String name, Object paramL10nObject) {
        if (name == null) {
            throw new IllegalArgumentException("name is null");
        }
        if (paramL10nObject == null) {
            throw new IllegalArgumentException("paramL10nObject is null");
        }
        paramMap.put(name, ExternalSourceUtils.toParam(name, paramL10nObject));
        return this;
    }

    public ExternalSourceType toExternalSourceType() {
        Object finalL10nObject = l10nObject;
        if (finalL10nObject == null) {
            finalL10nObject = new Litteral(name);
        }
        ExternalSourceType.Param[] array = paramMap.values().toArray(new ExternalSourceType.Param[paramMap.size()]);
        List<ExternalSourceType.Param> paramList = ExternalSourceUtils.wrap(array);
        return new InternalExternalSourceType(name, finalL10nObject, paramList);
    }

    public static ExternalSourceTypeBuilder init(String name) {
        return new ExternalSourceTypeBuilder(name);
    }


    private static class InternalExternalSourceType implements ExternalSourceType {

        private final String name;
        private final Object l10nObject;
        private final List<ExternalSourceType.Param> paramList;

        private InternalExternalSourceType(String name, Object l10nObject, List<ExternalSourceType.Param> paramList) {
            this.name = name;
            this.l10nObject = l10nObject;
            this.paramList = paramList;
        }

        @Override
        public String getName() {
            return name;
        }

        @Override
        public Object getL10nObject() {
            return l10nObject;
        }

        @Override
        public List<Param> getParamList() {
            return paramList;
        }

    }


}
