extends Node2D
export var action = "move_right"
export var velocity = Vector2(0.309,0.309)
export var press_limit = 3

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

var screen_size: Vector2
var tex_size: Vector2
var screen_stretch_factor: Vector2

func _unhandled_input(event: InputEvent) -> void:
    if(ControllerIcons.parse_event(event) == button.texture):
                press_limit -= 1
                if press_limit < -1:
                        # Should delete itself from the progress dictionary when destroyed
                        $AnimationPlayer.play("cease_4_exist")

func _ready() -> void:
    # Should save itself into the progress dictionary upon creation
    $Button/ControllerButton.path = action
    button.texture = $Button/ControllerButton.icon
    button.scale.x = 0.4
    button.scale.y = 0.4
    tex_size = Vector2(button.texture.get_width()/2, button.texture.get_height()/2) * button.scale * 0.75
    $Area/CollisionShape2D.shape.extents = tex_size

func _physics_process(delta: float) -> void:
        if(cam == null):
            cam = get_tree().root.get_child(3).get_node("%BlobbyCam")
            return
        button.texture = $Button/ControllerButton.icon
        # 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
        pass
    else:
        velocity.x *=-1

func _lesson_learned() -> void:
    levelState.absolved_tutorial(action)
    queue_free()
