extends Node2D
export var action1 = "move_right"
export var action2 = "boost_move" 
export var goal_state = ""
export var tutorial_text = ""
export var velocity = Vector2(0.309,0.309)
export var press_limit = 3
export var initial_wait_time:float = 0.0
export var start_moving_time: float = 30.0

onready var level_state := get_tree().root.get_child(4).get_node("%LevelState")
onready var cam = null
onready var blobby_state: AnimationNodeStateMachinePlayback = null
onready var button1 = $Button1
onready var button2 = $Button2

var screen_size: Vector2
var tex_size: Vector2
var screen_stretch_factor: Vector2
var rng = RandomNumberGenerator.new()
var moving = false
var tutorial_begun = false
var tutorial_area_entered = false

func check_goal_state() -> void:
	if(blobby_state == null):
		blobby_state = get_tree().root.get_child(4).get_node("%Blobby").get_node("%BlobbymationTree").get("parameters/playback")
	
	#print(blobby_state.get_current_node())
	if(blobby_state.get_current_node() == goal_state):
				press_limit -= 1
				if press_limit == -1 :
						# Should delete itself from the progress dictionary when destroyed
						if visible:
							$"%Label".visible = false
							$"%Label2".visible = false
							$TextureRect.visible = false
							$TextureRect2.visible = false
							$TextureRect3.visible = false
							$AudioStreamPlayer.play()
						$AnimationPlayer.play("cease_4_exist")

func _ready() -> void:
	# Should save itself into the progress dictionary upon creation
	if(!OS.is_debug_build()):
		level_state.register_tutorial(tutorial_text)
		if (!level_state.needs_tutorial(tutorial_text)): queue_free()
	if initial_wait_time > 0.0:
		var timer = Timer.new()
		add_child(timer)
		timer.wait_time = initial_wait_time
		timer.one_shot = true
		timer.connect("timeout",self,"finished_waiting")
		timer.start()
	$Button1/ControllerButton.path = action1
	$Button2/ControllerButton.path = action2
	$"%Label".text = tutorial_text
	button1.texture = $Button1/ControllerButton.icon
	button1.scale.x = 0.5
	button1.scale.y = 0.5
	button2.texture = $Button2/ControllerButton.icon
	button2.scale.x = 0.5
	button2.scale.y = 0.5
	tex_size = Vector2(button1.texture.get_width(), button1.texture.get_height()/2) * button1.scale * 0.75
	$Area/CollisionShape2D.shape.extents = tex_size
	$Area.monitorable = false
	set_physics_process(true)

func finished_waiting() -> void:
	if(tutorial_area_entered): start_tutorial()
	
func _physics_process(delta: float) -> void:
		check_goal_state()
		if(cam == null):
			cam = get_tree().root.get_child(4).get_node("%BlobbyCam")
			return
		button1.texture = $Button1/ControllerButton.icon
		button2.texture = $Button2/ControllerButton.icon
		if(moving == false): return
		# TODO process less in each frame
		var up_left_pos = cam.get_global_transform().affine_inverse() * (position - tex_size * self.scale) 
		var down_right_pos = cam.get_global_transform().affine_inverse() * (position + tex_size * self.scale)
		
		if up_left_pos.x <= cam.screen_left.x:
				velocity.x = abs(velocity.x)
		elif down_right_pos.x >= cam.screen_right.x:
				velocity.x = -abs(velocity.x)
		
		if up_left_pos.y <= cam.screen_top.y:
				velocity.y = abs(velocity.y)
		elif down_right_pos.y  >= cam.screen_bottom.y:
				velocity.y = -abs(velocity.y)
		
		self.position += velocity
		
		
	

func _on_Area_area_entered(area: Area2D) -> void:
	var d = area.global_position - position
	print(d)
	if(abs(d.y) > tex_size.y * 2 - 1):
		velocity.y *= -1
	else:
		velocity.x *=-1

func _lesson_learned(animation_name: String) -> void:
	if(animation_name != "cease_4_exist"): return
	moving = false
	if(!OS.is_debug_build()):
		level_state.absolved_tutorial(tutorial_text)
	blobby_state = null
	queue_free()

func start_tutorial():
	rng.randomize()
	#position.x += rng.randf_range(-100, 100) 
	#position.y += rng.randf_range(-100, 100)
	velocity.x = velocity.x * sign(rng.randf_range(-1,1))
	velocity.y = velocity.y * sign(rng.randf_range(-1,1))
	tutorial_begun = true
	var timer = Timer.new()
	add_child(timer)
	timer.wait_time = 0.2
	timer.one_shot = true
	timer.connect("timeout", self, "enable_visibility")
	timer.start()
	
	var start_moving_timer = Timer.new()
	add_child(start_moving_timer)
	start_moving_timer.wait_time = start_moving_time
	start_moving_timer.one_shot = true
	start_moving_timer.connect("timeout", self, "start_moving")
	start_moving_timer.start()


func start_moving() -> void:
	$Area.monitorable = true
	moving = true

func enable_visibility() -> void:
	visible = true

func _on_StartTutorialArea_area_entered(area: Area2D) -> void:
	tutorial_area_entered = true
	if(tutorial_begun || initial_wait_time > 0): return
	start_tutorial()
	
	# Erkenne ob der Spieler die Aktion für die das Tutorial ist schon kann
	# Wenn der Spieler den Tutorialbereich betritte spawne das Thingy random auf dem Screen
	# Füge zwei Inputs zusammen zu einem Thingy
