extends Popper
class_name Chat

var label
var tw = Tween.new()
var sp = AudioStreamPlayer3D.new()
var just_spawned
var buffer = Array()
signal buffer_ended
var cur_message = 0

var offset = Vector3(0,-8,0)

onready var clock = find_parent("MAIN").find_node("Clock")

func _process(delta):
	if Input.is_action_just_pressed("interact"):
		if just_spawned:
			just_spawned=false
			return
		#print("detecting input")
		read_buffer()
	just_spawned=false


func _ready():
	just_spawned = true
	#print("chat readying")
	add_child(tw)
	scale = Vector3(0.078,0.078,0.078)
	connect("buffer_ended",self,"end")
	clock.stop_time()
	#print("chat ready")
	get_parent().get_parent().root()
	
func end():
	if not clock.startlock:
		clock.start_time()
	get_parent().get_parent().PLAYER.end_chat()

func read_buffer():
	if buffer==null:
		return
	if cur_message<buffer.size():
		message(buffer[cur_message])
		cur_message+=1
	else:
		emit_signal("buffer_ended")
		cur_message=0
		buffer=null

func message(msg):
	play_sound()
	if label!=null:
		label.queue_free()
	label = Label3D.new()
	label.text = msg
	label.color = Color8(200,200,110)
	label.power = 2.0
	label.translation = offset
	tw.interpolate_property(label,"translation",offset,Vector3(0,0,0),1.0,Tween.TRANS_CUBIC,Tween.EASE_OUT)
	tw.start()
	add_child(label)

func close():
	queue_free()

# Called every frame. 'delta' is the elapsed time since the previous frame.
#func _process(delta):
#	pass
