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

public class AnimationComponent : MonoBehaviour
{
    private const string PARAM_DIRECTION = "Direction";
    private const string PARAM_SPEED = "Speed";

    public enum FacingDirection
    {
        Front = 0,
        Side = 1,
        Back = 2
    }

    private Animator m_Animator;

    private Transform m_AnimatorTransform;

    private Vector2 m_FacingDir;

    private void Awake()
    {
        m_Animator = GetComponentInChildren<Animator>();
        m_AnimatorTransform = m_Animator.transform;
    }

    public void SetFacing(Vector2 dir)
    {
        if (dir == m_FacingDir) return;

        // Vertical
        if (dir.x == 0)
        {
            if (m_AnimatorTransform.localScale.x < 0)
                Flip();

            // Up >> Back   |    Down >> Front
            if (dir.y > 0)
                m_Animator.SetFloat(PARAM_DIRECTION, (float)FacingDirection.Back);
            else
                m_Animator.SetFloat(PARAM_DIRECTION, (float)FacingDirection.Front);
        }
        else
        {
            if (m_FacingDir.x == 0)
            {
                m_Animator.SetFloat(PARAM_DIRECTION, (float)FacingDirection.Side);

                if (dir.x < 0)
                    Flip();
            }
            else
            {
                Flip();
            }
        }

        m_FacingDir = dir;
    }

    public void SetSpeed(float speed)
    {
        m_Animator.SetFloat(PARAM_SPEED, speed);
    }


    private void Flip()
    {
        Vector3 scale = m_AnimatorTransform.localScale;
        scale.x *= -1;
        m_AnimatorTransform.localScale = scale;
    }
}
