extends Spatial

export var recipes: Resource

# Called when the node enters the scene tree for the first time.
func _ready():
	assert(recipes != null)
	update_coin_machine_status()

func get_craft_recipe_item():
	var items_in_slots = [$slot_1.item_in_hold.item_type, $slot_2.item_in_hold.item_type]
	return recipes.find_recipe(items_in_slots)
	
func can_craft_recipe():
	return get_craft_recipe_item() != null

func craft_item():
	var crafted_item = get_craft_recipe_item()
	if crafted_item == null:
		return
	$slot_1.destroy_item()
	$slot_2.destroy_item()
	$craft_item_holder.spawn_item(crafted_item)	

func _on_coin_machine_coin_requirement_met(player):
	if not $slot_1.has_item():
		print("Slot 1 item missing")
		return
	if not $slot_2.has_item():
		print("Slot 2 item missing")
		return
	craft_item()
	
func should_enable_coin_machine():
	if $craft_item_holder.has_item():
		return false
	if not $slot_1.has_item() or not $slot_2.has_item():
		return false
	return can_craft_recipe()

func update_coin_machine_status():
	$coin_machine.enabled = should_enable_coin_machine()
	
func _on_craft_item_holder_item_changed(item):
	update_coin_machine_status()
	
func _on_slot_1_item_changed(item):
	update_coin_machine_status()

func _on_slot_2_item_changed(item):
	update_coin_machine_status()
