extends Damageable

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

enum EState {IDLE, WORKING, BLOCKED, BROKEN, NUM_STATES}

const States = {
EState.IDLE    : preload("res://scripts/crafting_station/state/idle.gd"),
EState.WORKING : preload("res://scripts/crafting_station/state/working.gd"),
EState.BLOCKED : preload("res://scripts/crafting_station/state/blocked.gd"),
EState.BROKEN  : preload("res://scripts/crafting_station/state/broken.gd")
}

const RepairKit : Resource = preload("res://item_types/repair_kit.tres")

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

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 = States[EState.BROKEN].new() if start_broken else States[EState.IDLE].new()
	state.ctx = self
	state.enter_from(null)
	print("crafting_station: NULL -> ", state.NAME)
	
	if start_broken:
		item_holder.spawn_item(RepairKit)

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

func change_state(new_state):
	print("crafting_station: ", state.NAME, " -> ", new_state.NAME)
	new_state.ctx = self
	state.exit_to(new_state)
	new_state.enter_from(state)
	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)

func _on_item_dump_item_dump_completed():
	state.on_item_dump_item_dump_completed()

func take_damage(damage : int = 1):
	.take_damage(damage)
	if state != null:
		state.on_damage_taken()
