extends Spatial

export var recipes: Resource
export var gen_time : float = 10.0

const StateIdle = preload("res://scripts/crafting_station/state/idle.gd")
const StateWorking = preload("res://scripts/crafting_station/state/working.gd")
const StateBlocked = preload("res://scripts/crafting_station/state/blocked.gd")

onready var item_holder = $"%item_holder"
onready var coin_machine = $"%coin_machine"
onready var gen_timer = $"%gen_timer"
onready var progress_text = $"%progress_text"

var item_slots = null
var state = null

func _ready():
	assert(recipes != null)
	recipes.validate()
	item_slots = get_tree().get_nodes_in_group("crafting_item_slots")
	assert(item_slots != null)
	for item_slot in item_slots:
		item_slot.connect("item_changed", self, "_on_slot_item_changed")

	gen_timer.wait_time = gen_time
	
	state = StateIdle.new()
	state.ctx = self
	state.enter_from(null)
	print("crafting_station: NULL -> ", state.NAME)

func _process(delta):
	state.update(delta)

func change_state(new_state, user_data = null):
	print("crafting_station: ", state.NAME, " -> ", new_state.NAME)
	new_state.ctx = self
	state.exit_to(new_state)
	new_state.enter_from(state, user_data)
	state = new_state

func _on_coin_machine_coin_requirement_met(player):
	state.on_coin_machine_coin_requirement_met(player)

func _on_gen_timer_timeout():
	state.on_gen_timer_timeout()

func _on_slot_item_changed(item):
	state.on_slot_item_changed(item)
	
func _on_item_holder_item_changed(item):
	state.on_item_holder_item_changed(item)
