/** 
* Copyright 2024 Brendan Robert
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/

package jace.config;

import java.util.Iterator;
import java.util.Map;

import jace.core.Utility;

/**
 *
 * @author Brendan Robert (BLuRry) brendan.robert@gmail.com 
 */
public abstract class DynamicSelection<T> implements ISelection<T> {
    public DynamicSelection(T defaultValue) {
        setValue(defaultValue);
    }
    abstract public boolean allowNull();
    T currentValue;
    @Override
    public T getValue() {
        if (currentValue != null || allowNull()) {
            return currentValue;
        } else {
            Iterator<? extends T> i = getSelections().keySet().iterator();
            if (i.hasNext()) {
                return i.next();
            } else {
                return null;
            }
        }
    }
    
    @Override
    public void setValue(T value) {currentValue = value;}
    
    @Override
    public void setValueByMatch(String search) {
        setValue(findValueByMatch(search));
    }

    public T findValueByMatch(String search) {
        Map<? extends T, String> selections = getSelections();
        String match = Utility.findBestMatch(search, selections.values());
        if (match != null) {
            for (T key : selections.keySet()) {
                if (selections.get(key).equals(match)) {
                    return key;
                }
            }
        }
        return null;
    }
}
