extends Node2D

const MAX_LENGTH = 256

enum {
	up = 0,
	down = 1,
	left = 2,
	right = 3
}

const dirs = [Vector2(1,0),Vector2(1,0),Vector2(0,1),Vector2(0,1)]

var destination
var custom_x
var custom_y
var direction = left


func setup(dir, dest="Test/TestRoom", custx=0, custy=0):
	direction = dir
	destination = dest
	custom_x = custx
	custom_y = custy
	

func _ready():
	if direction == down or direction == up:
		$RayCast2D.position.y += 24
		$RayCast2D.position.x += 1
		
	if direction == up:
		$RayCast2D.position.y -= 12
		
	if direction == left or direction == right:
		$RayCast2D.position.y += 1
	
	$RayCast2D.cast_to = dirs[direction] * MAX_LENGTH
	$RayCast2D.force_raycast_update()
	if $RayCast2D.is_colliding():
		$End.position = $RayCast2D.get_collision_point()
	else:
		$End.position = $RayCast2D.cast_to
	
	if direction == left or direction == right:
		position.y -= 32
		$Sprite.region_rect = Rect2(0,0,24,(transform.basis_xform_inv($End.position).y-global_position.y))
		$Area2D/CollisionShape2D.scale.y = ((transform.basis_xform_inv($End.position).y-global_position.y)/20)
		$Area2D/CollisionShape2D.position.y = (($Area2D/CollisionShape2D.scale.y*20)/2)-10
		
	if direction == right:
		position.x -= 8
		$Sprite.flip_h = false
		
	if direction == up or direction == down:
		$Sprite.texture = load("res://sprites/objects/transition/transition_down.png")
		$Sprite.region_rect = Rect2(0,0,transform.basis_xform_inv($End.position).x-global_position.x,24)
		$Area2D/CollisionShape2D.scale.x = (transform.basis_xform_inv($End.position).x-global_position.x)/20
		$Area2D/CollisionShape2D.position.x = get_midpoint().x-10
			
	if direction == up:
		position.y -= 8
		$Area2D.position.y += 10
		$Sprite.flip_v = true

	$RayCast2D.enabled = false
		
		
func get_midpoint():
	return $Sprite.region_rect.end/2


func _on_Area2D_body_entered(body):
	#Move to the next room when the player enters the transition
	if body.is_in_group("player"):
		game.entry_config(direction,custom_x,custom_y)
# warning-ignore:return_value_discarded
		get_tree().change_scene("res://rooms/"+destination+".tscn")
