from __future__ import annotations

from typing import TYPE_CHECKING

from random import choice as choice

import color
from components.base_component import BaseComponent
from input_handlers import GameOverEventHandler
from render_order import RenderOrder
import sound_engine
import animation_engine

if TYPE_CHECKING:
	from entity import Actor
	


class Fighter(BaseComponent):
	parent: Actor

	def __init__(self, hp: int, defense: int, power: int, hurtSound: sa.WaveObject, deathSound: sa.WaveObject):
		self.max_hp = hp
		self._hp = hp
		self.defense = defense
		self.power = power
		self.hurtSound = hurtSound
		self.deathSound = deathSound


	@property
	def hp(self) -> int:
		return self._hp
	

	@hp.setter
	def hp(self, value: int) -> None:
		self._hp = max(0, min(value, self.max_hp))
		if self._hp <= 0 and self.parent.ai:
			self.die()

	def die(self) -> None:
		if self.engine.player is self.parent:
			death_message = "You died! Will you be remembered?"
			death_message_color = color.player_die
			self.engine.event_handler = GameOverEventHandler(self.engine)
		else:
			death_message = f"{self.parent.name} is dead!"
			death_message_color = color.enemy_die

		self.parent.char = "%"
		self.parent.color = (255, 0, 0)
		self.parent.blocks_movement = False
		self.parent.ai = None
		self.parent.name = f"Remains of {self.parent.name}"
		self.parent.render_order= RenderOrder.CORPSE

		self.parent.bleed(amount=2)

		self.engine.sound_engine.emitSound(choice(self.deathSound))


		self.engine.message_log.add_message(death_message, death_message_color, makePing=False)

	def heal(self, amount: int) -> int:
		if self.hp == self.max_hp:
			return 0

		new_hp_value = self.hp + amount
		
		if new_hp_value > self.max_hp:
			new_hp_value = self.max_hp

		amount_recovered = new_hp_value - self.hp

		self.engine.animation_engine.emitAnimation(animation_engine.Highlight(cord=self.parent.xy,color=(0,150,0)))

		self.hp = new_hp_value

		return amount_recovered

	def take_damage(self, amount: int) -> None:
		self.hp -= amount
		self.parent.bleed(2)
		self.engine.animation_engine.emitAnimation(animation_engine.Highlight(cord=self.parent.xy,color=(255,50,50),duration=3,pulseLength=3))
		self.engine.sound_engine.emitSound(self.hurtSound)

	def makeHurtSound(self) -> None:
		self.engine.sound_engine.emitSound(self.hurtSound)