/* BdfServer - Copyright (c) 2009-2017 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.UiComponent;
import fr.exemole.bdfserver.api.ui.UiComponentFilter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;


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

    private final Set<String> excludeSet = new HashSet<String>();
    private final Map<String, UiComponent> replaceMap = new HashMap<String, UiComponent>();

    public UiComponentFilterBuilder() {

    }

    public void excludeUiComponent(UiComponent uiComponent) {
        excludeSet.add(uiComponent.getName());
    }

    public void replaceUiComponent(UiComponent uiComponent) {
        replaceMap.put(uiComponent.getName(), uiComponent);
    }

    public UiComponentFilter toComponentUiFilter() {
        return new InternalUiComponentFilter(excludeSet, replaceMap);
    }


    private static class InternalUiComponentFilter implements UiComponentFilter {

        private final Set<String> excludeSet;
        private final Map<String, UiComponent> replaceMap;

        private InternalUiComponentFilter(Set<String> excludeSet, Map<String, UiComponent> replaceMap) {
            this.excludeSet = excludeSet;
            this.replaceMap = replaceMap;
        }

        @Override
        public UiComponent filter(UiComponent uiComponent) {
            String keyString = uiComponent.getName();
            if (excludeSet.contains(keyString)) {
                return null;
            }
            UiComponent other = replaceMap.get(keyString);
            if (other != null) {
                return other;
            }
            return uiComponent;
        }

    }

}
