package uk.mgrove.ac.soton.comp1206.component;

import javafx.animation.FadeTransition;
import javafx.application.Platform;
import javafx.beans.property.SimpleListProperty;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.util.Duration;
import javafx.util.Pair;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * Class for displaying list of scores and associated users
 */
public class ScoresList extends VBox {

  /**
   * Logger
   */
  private static final Logger logger = LogManager.getLogger(ScoresList.class);

  /**
   * Scores
   */
  protected final SimpleListProperty<Pair<String,Integer>> scores = new SimpleListProperty<>(FXCollections.observableArrayList());

  /**
   * Title for scores list
   */
  protected Text title;

  /**
   * Initialise the scores list
   */
  public ScoresList(String titleText) {
    logger.info("Building scores list");

    setOpacity(0);

    title = new Text(titleText);
    title.getStyleClass().add("title");
    getChildren().add(title);

    scores.addListener((ListChangeListener<? super Pair<String, Integer>>) change -> Platform.runLater(() -> {
      logger.info("Detected change in scores list: {}", change);
      getChildren().clear();
      getChildren().add(title);
      for (var pair : scores.get()) {
        var individualScoreContainer = new HBox();
        individualScoreContainer.getChildren().addAll(new Text(pair.getKey()), new Text(pair.getValue().toString()));
        getChildren().add(individualScoreContainer);
      }
    }));
  }

  /**
   * Empty constructor
   */
  public ScoresList() {

  }

  /**
   * Bind scores to external property
   * @param scores external property to bind to
   */
  public void bindScores(SimpleListProperty<Pair<String,Integer>> scores) {
    this.scores.bindBidirectional(scores);
  }

  /**
   * Reveal the scores
   */
  public void reveal() {
    logger.info("Revealing scores");
    FadeTransition fadeInTransition = new FadeTransition(Duration.millis(1000), this);
    fadeInTransition.setToValue(1);
    fadeInTransition.play();
  }

}
