package eu.mhsl.minenet.minigames.score;

import eu.mhsl.minenet.minigames.message.Icon;
import eu.mhsl.minenet.minigames.message.TranslatableMessage;
import eu.mhsl.minenet.minigames.message.type.ChatMessage;
import eu.mhsl.minenet.minigames.message.type.TitleMessage;
import eu.mhsl.minenet.minigames.util.MapUtil;
import net.minestom.server.entity.Player;

import java.time.Duration;
import java.util.*;
import java.util.stream.Collectors;

public class PointsWinScore extends Score {
    private Map<Set<Player>, Integer> scoreOrder = new HashMap<>();

    @Override
    protected void insertResultImplementation(Set<Player> p, int currentPoints) {
        this.scoreOrder.put(p, currentPoints);
        this.scoreOrder = MapUtil.sortByValue(this.scoreOrder);
        getScores().clear();
        this.scoreOrder.forEach((player, integer) -> getScores().addFirst(player));
    }

    @Override
    protected void insertResultImplementation(Set<Player> p) {
        this.insertResultImplementation(p, 0);
    }

    @Override
    public void setDone() {
        if(isClosed()) return;
        close();
        new ChatMessage(Icon.STAR, true)
            .appendTranslated("score#result")
            .newLine()
            .indent()
            .numberedList(
                getScores()
                    .stream()
                    .filter(players -> !players.stream()
                        .filter(player -> !player.getUsername().isBlank())
                        .toList()
                        .isEmpty())
                    .map(players -> players
                        .stream()
                        .filter(player -> scoreOrder.get(Set.of(player)) != null)
                        .map(player -> player.getUsername()+" :  "+scoreOrder.get(Set.of(player)).toString())
                        .collect(Collectors.joining(", "))
                    )
                    .toList()
            )
            .undent()
            .newLine()
            .appendTranslated("score#thanks")
            .send(instance.getPlayers());

        instance.stop();
    }

    @Override
    protected TranslatableMessage scoreMessage() {
        return new TitleMessage(Duration.ofMillis(1000), Duration.ofSeconds(1)).appendTranslated("score#death");
    }
}
