extends StateMachine

onready var anim_tree = $"../FrogSprite/AnimationTree"
onready var anim_state_playback = $"../FrogSprite/AnimationTree".get("parameters/playback")


func _ready() -> void:
    add_state("searching")
    add_state("hunting")
    add_state("sleeping")
    state = states.searching
    set_state(states.searching)
    print(self.state)
    for state in states:
        if state_matching_method_exists(state):
            continue
        else:
            printerr("StateMachine -> State: " + state + " has no matching method in parent.")
            push_error("StateMachine -> State: " + state + " has no matching method in parent.")
    # _animation_logic()
        

# Game logic consequences of state
func _state_logic(delta):
    var state_action_ref = funcref(parent, self.state)
    parent.velocity = state_action_ref.call_func()
    parent.execute_movement(delta)


func _get_transition(_delta):
    parent.get_node("StateLabel").text = self.state
    _set_blendspaces_direction()
    _animation_logic()
    var new_state
    if parent.target == null:
        new_state = states.searching
    if parent.target != null:
        new_state = states.hunting
    if parent.is_hurt:
        new_state = states.sleeping
    if new_state != self.state:
        return new_state
    return null


func _enter_state(_new_state, _previous_state):
    pass


func _exit_state(_previous_state, _new_state):
    pass

func _animation_logic():    
    var animation = "sleeping"
    if parent.is_on_floor():
        if(parent.is_hurt):
            animation = "sleeping"
        elif (parent.is_bound):
            animation = "idleMean"
        else:
            animation = "idleHappy"
    # The frog is lifted from the ground slightly when blobby stands on him for whatever reason
    elif state != "sleeping":
        animation = "midJumping"
    if anim_state_playback.get_current_node() != animation:
        print(anim_state_playback.get_current_node())
        print(animation)
        anim_state_playback.travel(animation)


func _set_blendspaces_direction():
    var value = parent.get_facing_direction()
    # var leash_orientation := sign($"../LeashAnchor".position.x)
    # $"../LeashAnchor".position.x *= -1 if leash_orientation == value else 1
    anim_tree.set("parameters/idleHappy/blend_position", value)
    anim_tree.set("parameters/idleMean/blend_position", value)
    anim_tree.set("parameters/liftOff/blend_position", value)
    anim_tree.set("parameters/midJumping/blend_position", value)
    anim_tree.set("parameters/sleeping/blend_position", value)
