extends Spatial

export var gen_item : Resource
export var gen_time : float = 5.0
export var gen_count : int = 2

var item_slots

func _ready():
	assert(gen_item != null)
	item_slots = get_tree().get_nodes_in_group("item_slots")
	assert(item_slots != null)
	for item_slot in item_slots:
		item_slot.connect("item_changed", self, "_on_item_slot_item_changed")
	update_coin_machine_status()
	$"%gen_timer".one_shot = true
	$"%progress_text".visible = false
	
func update_progress_viz():
	if not $"%progress_text".visible:
		return
	var time_left : float = $"%gen_timer".time_left
	var time_passed : float = gen_time - time_left
	var percent_complete : float = (time_passed / gen_time) * 100.0
	$"%progress_text".text = "Progress: %.2f " % percent_complete
	
func _process(delta):
	update_progress_viz()
	
func is_generating() -> bool:
	return $"%gen_timer".time_left > 0

func start_generation():
	$"%progress_text".visible = true
	$"%gen_timer".start(gen_time)
	update_coin_machine_status()
	for item_slot in item_slots:
		item_slot.add_enabled = false

func _on_coin_machine_coin_requirement_met(player):
	assert(is_generator_ready())
	start_generation()
	
func is_generator_ready():
	for item_slot in item_slots:
		if item_slot.has_item():
			return false
	return not is_generating()

func update_coin_machine_status():
	$"%coin_machine".enabled = is_generator_ready()

#Note(asr): dynamically connect item_changed signal 
#on all nodes in the "item_slots" group. See _ready()
func _on_item_slot_item_changed(item):
	update_coin_machine_status()

func _on_gen_timer_timeout():
	var count : int = 0
	for item_slot in item_slots:
		if count < gen_count:
			item_slot.spawn_item(gen_item)
			count += 1
		item_slot.add_enabled = true
	update_coin_machine_status()
	$"%progress_text".visible = false
