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

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.text.Text;
import javafx.util.Pair;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * Component to display online leaderboard in multiplayer games
 */
public class Leaderboard extends ScoresList {

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

    /**
     * Scores - pair of username with pair of score and lives
     */
    private final SimpleListProperty<Pair<String,Pair<Integer,Integer>>> scores = new SimpleListProperty<>(FXCollections.observableArrayList());

    /**
     * Initialise the leaderboard
     */
    public Leaderboard(String titleText) {
        super();
        title = new Text(titleText);
        title.getStyleClass().add("heading");
        getChildren().add(title);

        reveal();
        scores.addListener((ListChangeListener<? super Pair<String,Pair<Integer, Integer>>>) change -> Platform.runLater(() -> {
            logger.info("Detected change in scores list: {}", change);
            getChildren().clear();
            getChildren().add(title);
            for (var pair : scores.get()) {
                var nameField = new Text(pair.getKey());
                if (pair.getValue().getValue() == -1) nameField.setStrikethrough(true);
                else nameField.setText(nameField.getText() + " (" + pair.getValue().getValue().toString() + ")");
                var scoreField = new Text(pair.getValue().getKey().toString());
                scoreField.getStyleClass().add("myscore");
                var individualScoreContainer = new HBox(nameField, scoreField);
                individualScoreContainer.setSpacing(8);
                getChildren().add(individualScoreContainer);
            }
        }));
    }

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

}
