class_name Enemy
extends Entity

signal hit_collider(collider:CollisionObject2D)

@export var physical_damage:float = 2.0
@export var damage_delay_secs:float = 0.5
#@export var visuals:Node2D

var player:Player
var damage_timer: float
var node_to_rotate:Node2D

var player_alive: bool:
	get: return player && player.is_alive

func _ready():
	get_player.call_deferred()
	#if visuals:
		#node_to_rotate = visuals
	#else:
		#node_to_rotate = self

func get_player():
	player = get_tree().get_first_node_in_group("player")
	
func dir_to_player() ->Vector2: 
	if player_alive:
		return global_position.direction_to(player.global_position)
	else:
		return Vector2.ZERO
		
func is_aim_ok(from_position:Vector2) -> bool:
	if !player_alive:
		return false
	# see if we are facing the player
	var to_plyr:Vector2 = from_position.direction_to(player.global_position)
	var dp:float = to_plyr.dot(-transform.y)
	return dp >= 0.98

func _process(delta: float) -> void:
	super._process(delta)
	if damage_timer > 0.0:
			damage_timer -= delta

func _physics_process(delta: float) -> void:
	super._physics_process(delta)
	if move_and_slide():
		var collision:KinematicCollision2D = get_slide_collision(0)
		var collider:CollisionObject2D = collision.get_collider()
		if collider:
			hit_collider.emit(collider)
			
		if physical_damage > 0.0 && collider == player && damage_timer <= 0.0 && player.sm.current_state_name != "to_grapple":
			collider.damage(physical_damage)
			damage_timer = damage_delay_secs
			
#region states
func _chase_player_fixed_update(delta: float) -> void:
	if player_alive:
		var dir:Vector2 = global_position.direction_to(player.global_position)
		rotate_to(self,dir,rotate_speed_deg * delta)
		velocity = velocity.move_toward(dir * speed, delta * acceleration) 
	else:
		velocity = velocity.move_toward(Vector2.ZERO, delta * acceleration / 2.0)

func _run_from_player_fixed_update(delta:float) -> void:
	if player_alive:
		var dir:Vector2 = global_position.direction_to(player.global_position)
		rotate_to(self,dir,rotate_speed_deg * delta)
		velocity = velocity.move_toward(-dir * speed, delta * acceleration) 
	else:
		velocity = velocity.move_toward(Vector2.ZERO, delta * acceleration / 2.0)
		
#endregion
