package gov.cms.grouper.snf.lego;

import java.util.function.Supplier;

public class SnfCache {

  public static class Reference<T> implements Supplier<T> {

    private T value;

    public Reference() {
      this(null);
    }

    public Reference(T value) {
      super();
      this.value = value;
    }

    @Override
    public T get() {
      return this.value;
    }

    public void set(T val) {
      this.value = val;
    }

  }

  public static class SupplierCache<T> implements Supplier<T> {

    private boolean init;
    private T result;
    private final Supplier<T> refresher;

    public SupplierCache(Supplier<T> refresher) {
      this.init = false;
      this.refresher = refresher;
    }

    public T refresh() {
      this.result = this.refresher.get();
      this.init = true;
      return this.result;
    }

    @Override
    public T get() {
      T value = this.result;
      if (init == false) {
        value = this.refresh();
      }
      return value;
    }

    @Override
    public String toString() {
      return "SupplierCache [result=" + result + "]";
    }

  }

  public static <T> SupplierCache<T> of(Supplier<T> refresher) {
    return new SupplierCache<T>(refresher);
  }

  public static <T> Reference<T> ofReference(T val) {
    return new Reference<>(val);
  }

  public static <T> Reference<T> of() {
    return ofReference(null);
  }

}
