extends Node2D

onready var balance_check_area = $balanced_check
onready var lever_body = $lever_RigidBody2D
onready var balance_score_timer = $balanced_check/Timer
onready var lever_body_id = lever_body.get_instance_id()
onready var balance_timer_label = $BalanceTimerLabel
onready var mode_label = $ModeLabel
onready var balance_check_sprite = $balanced_check/Sprite
onready var score_label = $MainScoreLabel/ScoreLabel
onready var time_label = $MainTimeLabel/TimeLabel
onready var main_game_timer = $MainGameTimer

var game_over = 0
var balance_score = 0
var main_score = 0
var ready = 0
var eating = 0
var main_game_time = 99
signal start_eating
signal end_game

func update_balance_counter(balance_count):
	balance_timer_label.text = str(balance_count)

func _on_balanced_check_body_entered(body):
	var entered_id = body.get_instance_id()
	if entered_id == lever_body_id and ready == 1:
		# print("balance_begin")
		balance_score_timer.start()
	pass

func _on_balanced_check_body_exited(body):
	var exited_id = body.get_instance_id()
	if exited_id == lever_body_id and ready == 1:
		# print("balance_broken")
		balance_score = 0
		update_balance_counter(balance_score)
		balance_score_timer.stop()
	pass

func _on_Timer_timeout():
	if ready == 1:
		balance_score += 1
		update_balance_counter(balance_score)
		mode_label.text = "BALANCE!"
		balance_score_timer.start()
	
	if balance_score >= 10 and eating == 0:
		print('balance score reached in seesaw.gd')
		balance_score_timer.stop()
		balance_score = 0
		eating = 1
		emit_signal("start_eating")
		mode_label.text = "EAT!"
		balance_check_sprite.visible = false
		balance_timer_label.visible = false
		ready = 0
	pass

func _on_ReadyArea2D_body_entered(body):
	if ready == 0 and eating == 0 and game_over == 0:
		ready = 1
		mode_label.text = "BALANCE!"
		main_game_timer.start()
		balance_score_timer.start()
	pass

func _on_Blower_stop_eating():
	print("BLOWER STOP EATING FIRED")
	mode_label.text = "BALANCE!"
	balance_check_sprite.visible = true
	balance_timer_label.visible = true
	balance_score = 0
	update_balance_counter(balance_score)
	eating = 0
	ready = 1
	pass

func _on_Blower_ate_flake():
	main_score += 1
	score_label.text = str(main_score)
	pass

func _on_MainGameTimer_timeout():
	if main_game_time > 0:
		main_game_time -= 1
		time_label.text = str(main_game_time)
	else:
		#end game
		time_label.text = "0"
		game_over = 1
		mode_label.text = "Score: " + str(main_score)
		ready = 0
	pass
