extends Node2D
export var action = "move_right"
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

var screen_size: Vector2
var tex_size: Vector2
var screen_stretch_factor: Vector2
var moving = false
var tutorial_begun = false
var tutorial_area_entered = false

onready var level_state := get_tree().root.get_child(4).get_node("%LevelState")
onready var cam = null
onready var button = $Button


func _unhandled_input(event: InputEvent) -> void:
	if event.is_action_pressed(action):
		press_limit -= 1
		if press_limit == 0:
			if visible:
				$"%Label".visible = false
				$TextureRect.visible = false
				$TextureRect2.visible = false
				$AudioStreamPlayer.play()
				$AnimationPlayer.play("cease_4_exist")
			else:
				queue_free()


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()
	$Button/ControllerButton.path = action
	$"%Label".text = tutorial_text
	button.texture = $Button/ControllerButton.icon
	button.scale.x = 0.5
	button.scale.y = 0.5
	tex_size = (
		Vector2(button.texture.get_width() / 2, button.texture.get_height() / 2)
		* button.scale
		* 0.75
	)
	$Area/CollisionShape2D.shape.extents = tex_size
	$Area.monitorable = false


func finished_waiting() -> void:
	if tutorial_area_entered:
		start_tutorial()


func _physics_process(_delta: float) -> void:
	if cam == null:
		cam = get_tree().root.get_child(4).get_node("%BlobbyCam")
		return
		
	if button.texture != $Button/ControllerButton.icon:
		button.texture = $Button/ControllerButton.icon

		# TODO process less in each frame
	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)
	position += velocity

func _on_Area_area_entered(area: Area2D) -> void:
	if !area.get_parent().visible:
		return
	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)
	queue_free()


func start_tutorial() -> void:
	var rng = RandomNumberGenerator.new()
	rng.randomize()
	#position = cam.get_global_transform() * position
	#position.x += prev_spawn_position.x + rng.randf_range(-40, 40)
	#position.y += prev_spawn_position.y + rng.randf_range(-40, 40)
	#prev_spawn_position = position
	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
