/*
 *   This file is a part of the SteamWar software.
 *
 *   Copyright (C) 2025 SteamWar.de-Serverteam
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Affero General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *   GNU Affero General Public License for more details.
 *
 *   You should have received a copy of the GNU Affero General Public License
 *   along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package de.steamwar.fightsystem.winconditions;

import de.steamwar.fightsystem.FightSystem;
import de.steamwar.fightsystem.countdown.Countdown;
import de.steamwar.fightsystem.fight.Fight;
import de.steamwar.fightsystem.fight.FightTeam;
import de.steamwar.fightsystem.states.StateDependentCountdown;
import lombok.Getter;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;

import java.util.ArrayList;
import java.util.List;
import java.util.function.ToDoubleFunction;
import java.util.stream.Collectors;

public abstract class Wincondition {

    @Getter
    protected static WinconditionBasePercent percentWincondition = null;
    protected static StateDependentCountdown timeOverCountdown = null;
    @Getter
    protected static final List<PrintableWincondition> printableWinconditions = new ArrayList<>();

    private final String windescription;

    protected Wincondition(String windescription) {
        this.windescription = windescription;
    }

    public static Countdown getTimeOverCountdown() {
        if (timeOverCountdown == null) return null;
        return timeOverCountdown.getCountdown();
    }

    protected void win(FightTeam team, String subtitle, Object... params) {
        FightSystem.setSpectateState(team, windescription, subtitle, params);
    }

    protected FightTeam isTarget(Entity player) {
        if (!(player instanceof LivingEntity)) return null;

        return Fight.getPlayerTeam((LivingEntity) player);
    }

    protected void comparisonWin(ToDoubleFunction<FightTeam> evaluate, String winMessage, String tieMessage) {
        double max = Fight.teams().stream().mapToDouble(evaluate).max().orElseThrow(() -> new SecurityException("No teams present"));
        List<FightTeam> teams = Fight.teams().stream().filter(team -> evaluate.applyAsDouble(team) == max).collect(Collectors.toList());
        if (teams.size() > 1) {
            win(null, tieMessage);
        } else {
            win(teams.get(0), winMessage, teams.get(0).getColoredName());
        }
    }
}
