extends CanvasLayer

var text
var length = 0
var scroll_effect = 0
var important = 0
var seconds = 0
var minutes = 0
onready var inventory = $Inventory.get_children()
onready var text_label = $DownPanel/Message
onready var scroll = text_label.get_v_scroll()
onready var clock = $UpPanel/CenterContainer/Timer

func _process(delta):
	$DownPanel.visible = (global.game_state == global.STATE.INGAME)
	$UpPanel.visible = (global.game_state == global.STATE.INGAME)
	$Inventory.visible = (global.game_state == global.STATE.INGAME)
	
func show_message(display_text,_important):
	$TypeTimer.stop()
	#$ScrollTimer.stop()
	#$ScrollWaitTimer.stop()
	$ClearTimer.stop()
	scroll_effect = 0
	scroll.value = 0
	text_label.visible_characters = 0
	text = display_text
	var regex
	regex = RegEx.new()
	regex.compile("\\[.*?]")
	var stripped = text
	for j in regex.search_all(text):
		stripped = stripped.replace(j.get_string(),"")
	length = stripped.length()
	#$ScrollWaitTimer.wait_time = 2
	$TypeTimer.start()
	$ClearTimer.start()
	#$ScrollWaitTimer.start()
	text_label.bbcode_text = text

func _on_TypeTimer_timeout():
	if scroll_effect == 0:
		if text_label.visible_characters < length:
			text_label.visible_characters += 1
		$TypeTimer.start()
	elif scroll_effect == -1 and text_label.visible_characters > 0:
		text_label.visible_characters -= 1
		$TypeTimer.start()

func _on_ScrollTimer_timeout():
	if scroll.value == scroll.max_value-9:
		$ScrollTimer.stop()
		$ScrollWaitTimer.stop()
		$ClearTimer.start()
	else:
		if scroll_effect < 9:
			scroll.value += 1
			scroll_effect +=1
		else:
			scroll_effect = 0
			$ScrollWaitTimer.start()
			$ScrollTimer.stop()

func _on_ScrollWaitTimer_timeout():
	text_label.visible_characters = length
	$ScrollWaitTimer.wait_time = 1
	$ScrollTimer.start()

func _on_ClearTimer_timeout():
	$TypeTimer.start()
	scroll_effect = -1

func update_items():
	for item in inventory:
		item.visible = global.has_item(item.name)

func run_clock():
	seconds = 0
	minutes = 0
	$ClockTick.start()

func stop_clock():
	$ClockTick.stop()
	

func update_clock():
	seconds += 1
	if seconds == 60:
		seconds = 0
		minutes += 1
	clock.text = ("%02d" % minutes) + ":" +("%02d" % seconds)
