extends Spatial
signal item_changed(item)

export var start_with_item : Resource
export var remove_enabled := true
export var add_enabled := true

var item_in_hold

# Called when the node enters the scene tree for the first time.
func _ready():
	if start_with_item != null:
		add_item(start_with_item.spawn_node())

func has_item() -> bool:
	return item_in_hold != null

func remove_item() -> Node:
	assert(item_in_hold != null)
	var removed_item = item_in_hold
	$ItemSpawn.remove_child(item_in_hold)
	item_in_hold = null
	return removed_item
	
func add_item(item):
	assert(item_in_hold == null)
	$ItemSpawn.add_child(item)
	item_in_hold = item

func spawn_item(item_type: Resource):
	assert(!has_item())
	assert(item_type is ItemType)
	add_item(item_type.spawn_node())
	emit_signal("item_changed", item_in_hold)

func destroy_item():
	var removed_item = item_in_hold
	$ItemSpawn.remove_child(item_in_hold)
	item_in_hold = null
	removed_item.queue_free()
	emit_signal("item_changed", item_in_hold)

func swap_with_player(player) -> bool:
	assert(has_item() and player.has_item())
	if not remove_enabled or not add_enabled:
		return false

	var player_item = player.drop_item_in_hand()
	player.pick_up_item(remove_item())
	add_item(player_item)
	
	$AudioStreamPlayer.play()
	emit_signal("item_changed", item_in_hold)
	return true

func give_to_player(player) -> bool:
	assert(has_item() and not player.has_item())
	if not remove_enabled:
		return false

	var player_item = player.pick_up_item(remove_item())

	$AudioStreamPlayer.play()
	emit_signal("item_changed", item_in_hold)
	return true

func take_from_player(player) -> bool:
	assert(not has_item() and player.has_item())
	if not add_enabled:
		return false
	
	add_item(player.drop_item_in_hand())

	$AudioStreamPlayer.play()
	emit_signal("item_changed", item_in_hold)
	return true

func on_player_interact(player) -> bool:
	if has_item() and player.has_item():
		return swap_with_player(player)
	elif has_item() and not player.has_item():
		return give_to_player(player)
	elif not has_item() and player.has_item():
		return take_from_player(player)
		
	var player_item = player.get_item_in_hand()
	if item_in_hold == null:
		if player_item == null:
			return false
		add_item(player_item)
	else:
		var item_pickup = remove_item()
		player.pick_up_item(item_pickup)
		$AudioStreamPlayer.play()
		if player_item != null:
			add_item(player_item)
	return true
