extends CharacterBody3D

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

func _ready():
	player = currentPlayer

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()
		switchImmune()
		print(immuneMesh)
		
	if !onDamageCooldown and dealingDamage:
		$"../wholePlayer"._takeDamage(20)
		onDamageCooldown = true
		$Timer.start(damageCooldown)
	
	for index in range(get_slide_collision_count()):
		# We get one of the collisions with the player
		var collision = get_slide_collision(index)

		# If there are duplicate collisions with an item in a single frame
		# the item will be deleted after the first collision, and a second call to
		# get_collider will return null, leading to a null pointer when calling
		# collision.get_collider().is_in_group("item").
		# This block of code prevents processing duplicate collisions.
		if collision.get_collider() == null:
			continue

		# If the collider is with an item
		if collision.get_collider().is_in_group("trap"):
			if !isImmune:
				queue_free()
				get_tree().change_scene_to_file(WholePlayer.getNextStage)
				
func switchTarget():
	if player == currentPlayer:
		player = otherBody
	else:
		player = currentPlayer

func switchImmune():
	if isImmune:
		isImmune = false
		immuneMesh.hide()
	else:
		isImmune = true
		immuneMesh.show()

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
