package gov.cms.grouper.snf.lego;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;

public class ActionWrapper<KEY, T> {

  private final Map<KEY, Pair<T, Function<T, T>>> actionMap = new HashMap<>();

  public ActionWrapper(List<Triple<T, KEY, Function<T, T>>> entries) {
    for (Triple<T, KEY, Function<T, T>> entry : entries) {
      T initValue = entry.getOne();
      KEY key = entry.getTwo();
      Function<T, T> action = entry.getThree();

      Pair<T, Function<T, T>> value = Pair.of(initValue, action);

      actionMap.put(key, value);
    }
  }

  public T doAction(KEY key) {
    Pair<T, Function<T, T>> value = actionMap.get(key);
    Function<T, T> action = value.getTwo();
    T currentValue = value.getOne();
    T newValue = action.apply(currentValue);

    value = Pair.of(newValue, action);
    actionMap.put(key, value);

    return newValue;
  }


  public T getValue(KEY key) {
    T result = null;
    Pair<T, Function<T, T>> value = actionMap.get(key);
    if (value != null) {
      result = value.getOne();
    }
    return result;
  }

  public Set<KEY> getAllKeys() {
    return actionMap.keySet();
  }

}
