package it.polimi.ingsw.gc14.Model.Cards.TribeCards.Events;

import it.polimi.ingsw.gc14.Model.Cards.TribeCards.EventType;
import it.polimi.ingsw.gc14.Model.Cards.TribeCards.EventCard;
import it.polimi.ingsw.gc14.Model.Player;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class ShamanicRitual extends EventCard {
    int prestigeToAdd;
    int prestigeToRemove;
    public ShamanicRitual(int Era, int prestigeToAdd, int prestigeToRemove) {
        super(Era, EventType.SHAMANIC_RITUAL);
        this.prestigeToAdd = prestigeToAdd;
        this.prestigeToRemove = prestigeToRemove;

    }

    @Override
    public void activateEvent (ArrayList <Player> playerList){
        Map<Player, Integer> playerMap = new HashMap<>();
        int tmpIcons = 0;
        int tmpCount = 0;

        for (Player player : playerList) {
            tmpIcons = player.shamans.stream().mapToInt(sh -> sh.getIcon()).sum();
            tmpCount = (int) player.buildingCards.stream().filter(b -> b.getEffectId() == 5).count();
            if (tmpCount >= 1) {
                tmpIcons = tmpIcons+(3*tmpCount);
            }
            playerMap.put(player, tmpIcons);
        }

        int maxIcon = playerMap.values().stream().mapToInt(Integer::intValue).max().orElse(0);
        int minIcon = playerMap.values().stream().mapToInt(Integer::intValue).min().orElse(0);

        List<Player> maxIconsPlayer = playerMap.entrySet().stream().filter(e -> e.getValue() == maxIcon).map(Map.Entry::getKey).collect(Collectors.toList());
        List<Player> minIconsPlayer = playerMap.entrySet().stream().filter(e -> e.getValue() == minIcon).map(Map.Entry::getKey).filter(player -> !maxIconsPlayer.contains(player)).collect(Collectors.toList());


        for (Player player : maxIconsPlayer) {
            if (player.buildingCards.stream().anyMatch(b -> b.getEffectId() == 6) && maxIconsPlayer.size() == 1) {
                player.addPrestige(prestigeToAdd * 2);
            } else {
                player.addPrestige(prestigeToAdd);
            }
        }

        for (Player player : minIconsPlayer) {
            if (!(player.buildingCards.stream().anyMatch(b -> b.getEffectId() == 2))) {
                player.removePrestige(prestigeToRemove);
            }
        }

    }
    @Override
    public EventCard clone() {
        return new ShamanicRitual(getEra(), prestigeToAdd, prestigeToRemove);
    }


}
