/* UtilLib - Copyright (c) 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 net.mapeadores.util.request;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;


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

    private final Map<String, List<String>> parameterMap = new HashMap<String, List<String>>();

    public RequestMapBuilder() {

    }

    public RequestMapBuilder addParameter(String name, String value) {
        List<String> currentList = parameterMap.get(name);
        if (currentList == null) {
            currentList = new ArrayList<String>();
            parameterMap.put(name, currentList);
        }
        currentList.add(value);
        return this;
    }

    public RequestMap toRequestMap() {
        Map<String, String[]> finalMap = new HashMap<String, String[]>();
        for (Map.Entry<String, List<String>> entry : parameterMap.entrySet()) {
            List<String> values = entry.getValue();
            if (!values.isEmpty()) {
                String[] finalValues = values.toArray(new String[values.size()]);
                finalMap.put(entry.getKey(), finalValues);
            }
        }
        return new InternalRequestMap(finalMap);
    }


    private static class InternalRequestMap implements RequestMap {

        private final Map<String, String[]> parameterMap;
        private final Set<String> nameSet;

        private InternalRequestMap(Map<String, String[]> parameterMap) {
            this.parameterMap = parameterMap;
            this.nameSet = Collections.unmodifiableSet(parameterMap.keySet());
        }

        @Override
        public FileValue getFileValue(String name) {
            return null;
        }

        @Override
        public FileValue[] getFileValues(String name) {
            return null;
        }

        @Override
        public String getParameter(String name) {
            String[] array = parameterMap.get(name);
            if (array == null) {
                return null;
            } else {
                return array[0];
            }
        }

        @Override
        public String[] getParameterValues(String name) {
            return parameterMap.get(name);
        }

        @Override
        public Set<String> getParameterNameSet() {
            return nameSet;
        }

        @Override
        public Locale[] getAcceptableLocaleArray() {
            return null;
        }

        @Override
        public Object getSourceObject() {
            return null;
        }

    }

}
