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

import fr.exemole.bdfserver.api.ui.CommentUi;
import fr.exemole.bdfserver.api.ui.UiComponent;
import fr.exemole.bdfserver.api.ui.UiComponents;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


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

    private final List<UiComponent> uiComponentList = new ArrayList<UiComponent>();
    private final Map<String, UiComponent> componentUiMap = new HashMap<String, UiComponent>();


    public UiComponentsBuilder() {

    }

    public UiComponentsBuilder addUiComponent(UiComponent componentUi) {
        String name = componentUi.getName();
        UiComponent currentComponentUi = componentUiMap.get(name);
        if (currentComponentUi != null) {
            if (currentComponentUi instanceof CommentUi) {
                uiComponentList.add(currentComponentUi);
            }
        } else {
            uiComponentList.add(componentUi);
            componentUiMap.put(name, componentUi);
        }
        return this;
    }

    public UiComponents toUiComponents() {
        List<UiComponent> finalUiComponentList = UiUtils.wrap(uiComponentList.toArray(new UiComponent[uiComponentList.size()]));
        Map<String, UiComponent> cloneComponentUiMap = new HashMap<String, UiComponent>(componentUiMap);
        return new InternalUiComponents(finalUiComponentList, cloneComponentUiMap);
    }

    public static UiComponentsBuilder init() {
        return new UiComponentsBuilder();
    }


    private final static class InternalUiComponents implements UiComponents {

        private final List<UiComponent> uiComponentList;
        private final Map<String, UiComponent> componentUiMap;

        private InternalUiComponents(List<UiComponent> uiComponentList, Map<String, UiComponent> componentUiMap) {
            this.uiComponentList = uiComponentList;
            this.componentUiMap = componentUiMap;
        }

        @Override
        public List<UiComponent> getUiComponentList() {
            return uiComponentList;
        }

        @Override
        public UiComponent getUiComponent(String keyString) {
            return componentUiMap.get(keyString);
        }

    }

}
