extends Reference

const NAME = "idle"

var ctx = null
var item_to_craft = null

func _init():
	pass

func enter_from(state):
	for item_slot in ctx.item_slots:
		item_slot.add_enabled = true
		item_slot.remove_enabled = true
	ctx.item_holder.add_enabled = true
	ctx.item_dump.enabled = false
	ctx.progress_text.text = "Ready!"
	update_coin_machine_status()

func exit_to(state):
	pass

func update(delta):
	pass

func on_coin_machine_coin_requirement_met(player):
	item_to_craft = get_craft_recipe_item()
	assert(item_to_craft != null)
	ctx.change_state(ctx.States[ctx.EState.WORKING].new(item_to_craft) )

func on_gen_timer_timeout():
	assert(false, "gen timer shouldn't trigger while idle")

func on_slot_item_changed(item):
	# enable coin machine if you have a valid combo of items
	update_coin_machine_status()

func on_item_holder_item_changed(item):
	# if target spot is occupied, go to blocked state
	if item != null:
		ctx.change_state(ctx.States[ctx.EState.BLOCKED].new("Blocked!"))

func on_item_dump_item_dump_completed():
	pass

func on_damage_taken():
	if ctx.current_hp <= 0:
		ctx.change_state(ctx.States[ctx.EState.BROKEN].new())
	
func get_craft_recipe_item():
	var items_in_slots = []
	for item_slot in ctx.item_slots:
		if item_slot.has_item():
			items_in_slots.append(item_slot.item_in_hold.item_type)
	if items_in_slots.empty():
		return null
	return ctx.recipes.find_recipe(items_in_slots)

func update_coin_machine_status():
	var can_craft_recipe : bool = get_craft_recipe_item() != null
	ctx.coin_machine.enabled = can_craft_recipe
	if can_craft_recipe:
		ctx.status_light.prime()	
	else:
		ctx.status_light.idle()
