# arenaUI

# models
from models.heroes.hero import Hero

from sty import fg

from random import randint

# pour éviter les pb d'import circulaire
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from controllers.PvpController import PvpController


class ArenaUI:
    def __init__(self, pvpController: "PvpController") -> None:
        self.pvpController = pvpController
        self.hero = self.pvpController.hero
        self.opponent = self.pvpController.opponent

        self.init()

        self.pvpController.hero = self.hero

    def init(self):
        print("You go into the arena")
        print(f"Are you {fg.green} ready {fg.rs} ?")
        print("Anyway, no choice ^^")

        print(f"You will {fg.red} fight {fg.red}against{self.opponent.name}")

        if self.hero.type == Hero.ARCHERY:
            print("You begin")
            self.attacks(self.hero, self.opponent)
        else:
            print(f"{self.opponent.name} begin")

        self.fight()

    def fight(self):
        while self.hero.HP > 0 and self.opponent.HP > 0:
            self.attacks(self.hero, self.opponent)

            if self.opponent.HP > 0:
                self.attacks(self.opponent, self.hero, True)

        if self.hero.HP > 0:
            print(f"You {fg.blue}won{fg.rs} !")
        elif self.opponent.HP > 0:
            print(f"{self.opponent.name} {fg.red}beat{fg.rs} you")
        else:
            raise Exception("An error occured")

    def attacks(self, hero: Hero, opponent: Hero, is_AI: bool = False):
        print(f"Choose an attack - {hero.name} will ...")

        attacks_list = hero.attacks_choice
        attacks_list_len = len(attacks_list)

        choice = -1
        while choice < 1 or choice > attacks_list_len:
            for i in range(0, attacks_list_len):
                print(f"{i+1} - {attacks_list[i]}")

            try:
                if is_AI:
                    choice = randint(1, attacks_list_len + 1)
                else:
                    choice = int(input("Give your choice: "))
            except ValueError:
                print(f"{fg.red}Input a valid number{fg.rs}")
                continue

            if choice < 1 or choice > attacks_list_len:
                print(f"{fg.red}Invalid choice. Try again{fg.rs}")

        print(f"You choose {attacks_list[choice-1]}")

        if choice == 1:
            opponent.HP -= hero.attacks(opponent)
        elif choice == 2:
            hero.cure()
