extends Node2D

export var b1 = 1
export var b2 = 2
export var b3 = 3

var bdir = 0
var hold
var rng = RandomNumberGenerator.new()
var gameover = false

var cycletimer = 0

const CYCLEL = 40

signal checkifsolid(x,y, b1, b2, b3)
signal checkifsolid2(x,y, b1, b2, b3, dir)
signal checkifsolid3(x,y, b1, b2, b3, dir)
signal tellblocks(b1, b2, b3)

# 0 = red
# 1 = blue
# 2 = yellow
# 3 = green
# Called when the node enters the scene tree for the first time.
func _ready():
	randoBlocks()
	setColor()
	
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
	if(bdir == 0):
		$S4.hide()
		$S5.hide()
		$S2.show()
		$S3.show()
	elif(bdir==1):
		$S2.hide()
		$S3.hide()
		$S4.show()
		$S5.show()
	
	
	if(!gameover):
		
		if(Input.is_action_just_pressed("Cycle Down")):
			cycle(0)
	
		if(Input.is_action_just_pressed("Cycle Up")):
			cycle(1)
		
		if(Input.is_action_pressed("Move Down")):
			cycletimer = cycletimer+2
			
		if(Input.is_action_just_pressed("Move Left")):
			if(bdir == 0):
				emit_signal("checkifsolid2", (get_position().x-32)/64, (get_position().y-32)/64, b1, b2, b3, 0)
			else:
				emit_signal("checkifsolid3", (get_position().x-32)/64, (get_position().y-32)/64, b1, b2, b3, 0)
		if(Input.is_action_just_pressed("Move Right")):
			if(bdir == 0):
				emit_signal("checkifsolid2", (get_position().x-32)/64, (get_position().y-32)/64, b1, b2, b3, 1)
			else:
				emit_signal("checkifsolid3", (get_position().x-32)/64, (get_position().y-32)/64, b1, b2, b3, 1)

	
		if(cycletimer < CYCLEL):
			cycletimer = cycletimer+1
		else:
			cycletimer = 0
			emit_signal("checkifsolid", (get_position().x-32)/64, (get_position().y-32)/64, b1, b2, b3)



func setColor():
	$S1.frame = b1
	$S2.frame = b2
	$S3.frame = b3
	$S4.frame = b2
	$S5.frame = b3
	
func cycle(direction):
	if(direction == 1):
		#cycle up 
		hold = b3
		b3 = b2
		b2 = b1
		b1 = hold
		setColor()
		print(b1)
		print(b2)
		print(b3)
	elif(direction == 0):
		#cycle down
		hold = b1
		b1 = b2
		b2 = b3
		b3 = hold
		setColor()
		print(b1)
		print(b2)
		print(b3)
	
	pass

func moveDown():
	self.position.y = get_position().y + 64
	pass
func moveLeft():
	self.position.x = get_position().x - 64
	pass
func moveRight():
	self.position.x = get_position().x + 64
	pass

func moveUp():
	self.position.y = get_position().y - 64
	pass



func reset():
	if(bdir == 1):
		self.position.y = -32
		self.position.x = 288
		bdir = 0
	else:
		self.position.x = -32
		self.position.y = 288
		bdir = 1
	randoBlocks()
	print(b1)
	print(b2)
	print(b3)
	setColor()

func randoBlocks():
	rng.randomize()	
	hold = round(rng.randf_range(1, 4))
	if(hold > 4):
		hold = 4
	b1 = hold
	rng.randomize()	
	hold = round(rng.randf_range(1, 4))
	if(hold > 4):
		hold = 4
	b2 = hold
	rng.randomize()	
	hold = round(rng.randf_range(1, 4))
	if(hold > 4):
		hold = 4
	b3 = hold
	
	emit_signal("tellblocks", b1, b2, b3)
