extends Control

const ITEM_TEXTURE_RECT = preload("res://Items/ItemTextureRect.tscn")

signal item_choosen(item)

onready var h_box_container = $CenterContainer/VBoxContainer/CenterContainer2/HBoxContainer
onready var texture_progress = $CenterContainer/VBoxContainer/CenterContainer/TextureProgress
onready var label = $CenterContainer/VBoxContainer/Label
#onready var cursor = $Cursor
onready var timer = $Timer

export (Array, Resource) var items = []
var selected = 0
var is_long_tap = false

func _ready():
	for item in items:
		add_item(item)
	set_item_container_selected(true)

func set_item_container_selected(enable):
	var slot = h_box_container.get_child(selected)
	if slot != null:
		slot.selected = enable
		label.text = items[selected].description
	#print("Cursor pos: ", cursor.global_position)
	#print("Rect pos: ", h_box_container.get_child(selected).rect_global_position)

func add_item(item):
	if item is Item:
		var item_texture_rect = ITEM_TEXTURE_RECT.instance()
		h_box_container.add_child(item_texture_rect)
		item_texture_rect.get_node("ItemTextureRect").texture = item.texture

func _process(_delta):
	if h_box_container.get_child_count() == 0:
		return
	if Input.is_action_just_released("action"):
		timer.stop()
		if not is_long_tap:
			short_tap()
	
	if Input.is_action_just_pressed("action"):
		is_long_tap = false
		timer.start()
	if timer.time_left > timer.wait_time-0.2:
		texture_progress.value = 0
	else:
		texture_progress.value = timer.time_left

func short_tap():
	set_item_container_selected(false)
	Audio.play_sound_random(["WindUp", "WindUp2"])
	selected += 1
	if selected > h_box_container.get_child_count()-1:
		selected = 0
	set_item_container_selected(true)

func long_tap():
	var item = items[selected]
	print(item)
	$Tween.interpolate_property(self, "rect_size", rect_size, Vector2(rect_size.x, 0), 0.5, Tween.TRANS_QUINT, Tween.EASE_IN_OUT)
	$Tween.start()
	Audio.play_sound("ItemGrab")
	yield($Tween, "tween_all_completed")
	emit_signal("item_choosen", item)
	queue_free()

func _on_Timer_timeout():
	long_tap()
	is_long_tap = true
	print("long")
