extends CharacterBody3D


const SPEED = 5.0
const JUMP_VELOCITY = 4.5

var firstInventorySelected = true
var inventory1: Array[String] = []
var inventory2: Array[String] = []
var sceneInventory1: Array[Node] = []
var sceneInventory2: Array[Node] = []
var inventory_text: Control
@onready var anim_player = $AnimationPlayer
@onready var hitbox = $WeaponPivot/WeaponMesh/Hitbox

func _ready() -> void:
	inventory_text = get_tree().get_first_node_in_group("inventory_panel")

func _process(delta: float) -> void:
	if Input.is_action_just_pressed("Attack"):
		attack_swing()
	
	if Input.is_action_just_pressed(("Throw")):
		print("throwing")
		throw_item()

func _physics_process(delta: float) -> void:
	# Add the gravity.
	if not is_on_floor():
		velocity += get_gravity() * delta

	# Handle jump.
	if Input.is_action_just_pressed("Jump") and is_on_floor():
		velocity.y = JUMP_VELOCITY

	# Get the input direction and handle the movement/deceleration.
	# As good practice, you should replace UI actions with custom gameplay actions.
	var input_dir := Input.get_vector("Move Left", "Move Right", "Move Forward", "Move Backward")
	var direction := (transform.basis * Vector3(input_dir.x, 0, input_dir.y)).normalized()
	if direction:
		velocity.x = direction.x * SPEED
		velocity.z = direction.z * SPEED
	else:
		velocity.x = move_toward(velocity.x, 0, SPEED)
		velocity.z = move_toward(velocity.z, 0, SPEED)

	move_and_slide()
	
	# Iterate through all collisions that occurred this frame
	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("item"):
			var item = collision.get_collider()
			add_item(item)
			#item.queue_free();
			# Prevent further duplicate calls.
			break
		if collision.get_collider().is_in_group("door"):
			var door = collision.get_collider()
			if (inventory1 if firstInventorySelected else inventory2).has(door.needs_item):
				door.queue_free()
				break

func add_item(new_item):
	(inventory1 if firstInventorySelected else inventory2).append(new_item.item_name)
	if inventory_text:
		inventory_text.update_inventory((inventory1 if firstInventorySelected else inventory2), firstInventorySelected)
	
	(sceneInventory1 if firstInventorySelected else sceneInventory2).append(new_item)
	
	new_item.set_freeze_enabled(true)
	new_item.set_visible(false)
	new_item.disable_item()

func attack_swing():
	anim_player.play("horizontal_swing")
	hitbox.monitoring = true;
	
func throw_item():
	if((sceneInventory1 if firstInventorySelected else sceneInventory2)):
		var next_item = (sceneInventory1 if firstInventorySelected else sceneInventory2)[0]
		(inventory1 if firstInventorySelected else inventory2).erase(next_item.item_name)
		if inventory_text:
			inventory_text.update_inventory((inventory1 if firstInventorySelected else inventory2), firstInventorySelected)
		next_item.set_freeze_enabled(false)
		next_item.enable_item()
		#Setting the item in front of player
		var forward = -global_transform.basis.z.normalized()
		var upward = global_transform.basis.y.normalized()
		var spawn_offset = 1.5
		next_item.global_position = global_transform.origin + forward * spawn_offset + Vector3.UP * 1.2 + upward
		next_item.set_visible(true)
		
		#Applies Impulse to item
		var dir = -global_transform.basis.z.normalized()
		next_item.apply_impulse(dir * 6.0)
		(sceneInventory1 if firstInventorySelected else sceneInventory2).erase(next_item)
	

func _on_animation_player_animation_finished(anim_name: StringName) -> void:
	if anim_name == "horizontal_swing":
		hitbox.monitoring = false;

func _on_hitbox_body_entered(body: Node3D) -> void:
	if body.is_in_group("enemy") and body.is_in_group("immuneEnemy"):
		print("hit immuneEnemy")
		if !body.isImmune:
			body.queue_free()
	elif body.is_in_group("enemy"):
		print("hit enemy!")
		body.queue_free()

func swap_inventory() -> void:
	firstInventorySelected = !firstInventorySelected
	if inventory_text:
		inventory_text.update_inventory((inventory1 if firstInventorySelected else inventory2), firstInventorySelected)
	
