using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DrivingAnimation : StateMachineBehaviour
{
    [SerializeField]
    private string driftingVariableName = "Drifting";

    [SerializeField]
    private string directionVariableName = "DriftRight";

    [SerializeField]
    private string endDriftVariableName = "EndDrift";

    [SerializeField]
    private string floatVariableName = "InputX";

    [SerializeField]
    private RacerCore Core;

    override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        CheckForCore(animator.transform);
    }

    void CheckForCore(Transform parent)
    {
        if (parent)
            Core = parent.GetComponent<RacerCore>();

        if (!Core && parent.parent)
        {
            CheckForCore(parent.parent);
        }
    }

    override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        if (!Core)
        {
            CheckForCore(animator.transform);
            return;
        }

        // Set the steering value to the horizontal input of the controller
        animator.SetFloat(floatVariableName, Core.Controller.XYInput.x);

        // If we are drifting...
        if (Core.Controller.Drifting)
        {
            // But we have not entered the drifting animation yet...
            if (!animator.GetBool(driftingVariableName))
            {
                // Set the direction of the drift in the animator
                animator.SetBool(directionVariableName, Core.Controller.DriftRight);
            }
        }
        else {
            // If we are no longer drifting but our animator is still in the drifting state...
            if (animator.GetBool(driftingVariableName))
            {
                animator.SetBool(endDriftVariableName, true);
            }
        }
        
        // Set the drifting boolean of the animator to true
        animator.SetBool(driftingVariableName, Core.Controller.Drifting);
    }
}
