extends CharacterBody3D

var speed = 1.0
var damageCooldown = 2.0
@onready var currentPlayer = $"../wholePlayer/Player"
@onready var otherBody = $"../wholePlayer/OtherBody"
var directionVector
var player
var onDamageCooldown = false
var dealingDamage = false

func _ready():
	if !player:
		player = otherBody
	
func _physics_process(_delta):
	if player:
		look_at(player.global_transform.origin, Vector3.UP)
		directionVector = (player.global_transform.origin - global_transform.origin)
		directionVector.y = 0
		directionVector = directionVector.normalized()
		velocity = directionVector * speed
		move_and_slide()
		
		# Rotate to face player
		look_at(Vector3(player.global_position.x, global_position.y, player.global_position.z), Vector3.UP)
		
	if Input.is_action_just_pressed("Swap"):
		switchTarget()
		
	if !onDamageCooldown and dealingDamage:
		$"../wholePlayer"._takeDamage(20)
		onDamageCooldown = true
		$Timer.start(damageCooldown)
		
func switchTarget():
	if player == currentPlayer:
		player = otherBody
	else:
		player = currentPlayer

func setFirstTarget(target):
	player = target


func _on_area_3d_body_entered(body: Node3D) -> void:
	if body == currentPlayer or body == otherBody:
		dealingDamage = true
		
func _on_area_3d_body_exited(body: Node3D) -> void:
	if body == currentPlayer or body == otherBody:
		dealingDamage = false
		
func _on_timer_timeout() -> void:
	onDamageCooldown = false
