# buff_system.py : buffs joueurs (immunites, vitesse, sorts divins)
# un buff = {"type": "...", "timer": float, ...} dans player.buffs

import logging

from constants import (
    ALDRIC_FLYING_SPEED_MULT,
    TICK_DURATION,
)

logger = logging.getLogger(__name__)


def player_has_buff(player, buff_type):
    return any(b["type"] == buff_type for b in player.buffs)


def player_is_immune(player):
    """immunise aux degats si invuln/intangible/flying.

    invuln = sort divin Kael, intangible = teleport Seris, flying = vol Aldric
    """
    return any(b["type"] in {"invulnerable", "intangible", "flying"} for b in player.buffs)


def player_damage_mult(player):
    mult = 1.0
    for b in player.buffs:
        if b["type"] in ("damage_mult", "combat_buff"):
            mult *= b.get("damage_mult", 1.0)
    return mult


def player_speed_mult(player):
    # on prend le max et pas le produit : 2 buffs vitesse en meme temps doivent pas se cumuler a fond
    mult = 1.0
    for b in player.buffs:
        if b["type"] == "flying":
            mult = max(mult, ALDRIC_FLYING_SPEED_MULT)
        elif b["type"] in ("speed_mult", "combat_buff"):
            mult = max(mult, b.get("speed_mult", 1.0))
    return mult


def update_buffs(state):
    # decremente les timers de tous les buffs, vire les expires
    for player in state.players:
        kept = []
        for buff in player.buffs:
            buff["timer"] = max(0.0, buff["timer"] - TICK_DURATION)
            if buff["timer"] > 0:
                kept.append(buff)
            # TODO si on rajoute des effets en fin de buff, c'est ici
        player.buffs = kept
