
extends Panel

var PackedButton
const ButtonInterval = 1.5
var interval = 0
var CurrentType = 0
var RitualLabel
var ButtonLayer
var Reagan
var ReaganInitialPos
var ReaganPos
var ReaganSize
var CurrentScore = 0
var CurrentString = ""
var InitialScore = 3.0
var DisplayScore = 0
var TargetScore = 20.0
var TransitionRate = 0.3
var Ready = false

var currentSlot = 0
var slotValues = [ [0, 0], [0, 0] ]

func _ready():
	PackedButton = ResourceLoader.load("res://TextComponentButton.scn")
	RitualLabel = get_node("RitualLabel")
	Reagan = get_node("Table/Reagan")
	ButtonLayer = get_node("ButtonLayer")
	ReaganInitialPos = Reagan.get_pos()
	ReaganPos = Reagan.get_pos()
	ReaganSize = Reagan.get_size().y
	set_process(true)
	ButtonLayer.set_process(true)
	CurrentScore = InitialScore

func AddFloatingButton():
	var button = PackedButton.instance()
	button.connect("ButtonClicked", self, "_OnButtonClicked")
	button.setType(CurrentType)
	CurrentType = (CurrentType + 1) % 4
	ButtonLayer.add_child(button)

func _on_IntroLabel_exit_tree():
	Ready = true

func _process(delta):
	if DisplayScore < CurrentScore:
		DisplayScore += TransitionRate * delta
		if DisplayScore > CurrentScore:
			DisplayScore = CurrentScore
	else:
		DisplayScore -= TransitionRate * delta
		if DisplayScore < CurrentScore:
			DisplayScore = CurrentScore
		
	ReaganPos.y = ReaganInitialPos.y - ReaganSize * (DisplayScore / TargetScore)
	Reagan.set_pos(ReaganPos)
	
	if Ready:
		interval += delta
		if interval >= ButtonInterval:
			AddFloatingButton()
			interval -= ButtonInterval

func _EndGame(victory):
	Ready = false
	if victory:
		RitualLabel.set_text("We have revived the great Reagan! We now will usher in a new era of greatness for the wealthy over everyone else!")
	else:
		RitualLabel.set_text("We have lost Reagan forever. Now the poor will have better lives at the expense of the richest")

func _OnButtonClicked(entryType, entryValue, entryString):
	if Ready:
		if currentSlot >= slotValues.size():
			CurrentString = ""
			currentSlot = 0
		
		if CurrentString:
			CurrentString += " "
		CurrentString += entryString
		RitualLabel.set_text(CurrentString)
		
		slotValues[currentSlot][0] = entryType
		slotValues[currentSlot][1] = entryValue
		currentSlot += 1
		if currentSlot >= slotValues.size():
			# Evaulate slots
			if (slotValues[0][0] == 0 and slotValues[1][0] == 3) or (slotValues[0][0] == 1 and slotValues[1][0] == 2):
				CurrentScore += 1
				if CurrentScore >= TargetScore:
					_EndGame(true)
			else:
				CurrentScore -= 1
				if CurrentScore <= 0:
					_EndGame(false)
