package patterns.observable;

import java.util.ArrayList;
import java.util.List;

class HighscoreList {

  private int maxSize;
  private List<Integer> results;
  private List<HighscoreListListener> listeners;

  public HighscoreList(int maxSize) {
    this.maxSize = maxSize;
    this.results = new ArrayList<>();
    this.listeners = new ArrayList<>();
  }

  public int size() {
    return results.size();
  }

  public int getElement(int n) {
    return results.get(n);
  }

  public void addResult(int result) {

    int i = 0;

    if (results.isEmpty())
      results.add(result);

    else {
      while (i + 1 < results.size() && results.get(i) <= result)
        i++;

      if (i + 1 == results.size())
        results.add(result);
      else
        results.add(i, result);
    }

    if (results.size() > maxSize)
      results.remove(maxSize);

    System.out.println(results);
    System.out.println(i);

    boolean elementWasDeleted = i + 1 == this.maxSize;

    for (var listener : listeners)
      listener.listChanged(this, elementWasDeleted ? -1 : i);

  }

  public void addHighscoreListListener(HighscoreListListener listener) {
    this.listeners.add(listener);
  }

  public void removeHighscoreListListener(HighscoreListListener listener) {
    this.listeners.remove(listener);
  }
}