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 {
    Map<Set<Player>, Integer> scoreOrder = new HashMap<>();

    @Override
    protected void insertResultImplementation(Set<Player> p, int currentPoints) {
        Set<Player> combined = this.scoreOrder.entrySet().stream()
            .filter(entrySet -> Objects.equals(entrySet.getValue(), currentPoints))
            .map(Map.Entry::getKey)
            .findFirst()
            .orElseGet(() -> {
                Set<Player> s = new HashSet<>();
                this.scoreOrder.put(s, currentPoints);
                return s;
            });
        combined.addAll(p);

        this.scoreOrder = MapUtil.sortByValue(this.scoreOrder);
        this.getScores().clear();
        this.scoreOrder.forEach((player, integer) -> this.getScores().addFirst(player));
    }

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

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

        this.instance.stop();
    }

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