using UnityEngine;
using System.Collections;

[RequireComponent(typeof(Animator))]
public class AnimationManager : MonoBehaviour
{
    private Animator _animator;
    private AnimatorStateBehaviour[] _behaviours;
    private AnimatorStateBehaviour _currentBehaviour;

    void Awake()
    {
        _animator = GetComponent<Animator>();
    }

    // Use this for initialization
    void Start()
    {
    }

    public void SetState(int stateIndex)
    {
        _animator.SetInteger("State", stateIndex);
        _animator.SetTrigger("ChangeState");

        _currentBehaviour = null;

        if (_behaviours == null)
        {
            _behaviours = _animator.GetBehaviours<AnimatorStateBehaviour>();
        }

        foreach (AnimatorStateBehaviour behaviour in _behaviours)
        {
            if (behaviour.AnimationIndex == stateIndex)
            {
                _currentBehaviour = behaviour;
                break;
            }
        }
    }

    public int? GetState()
    {
        if (_currentBehaviour == null)
        {
            return null;
        }

        return _currentBehaviour.AnimationIndex;
    }

    public bool IsStateActive(int stateIndex)
    {
        return (_currentBehaviour != null && _currentBehaviour.AnimationIndex == stateIndex && _currentBehaviour.IsAnimationActive());
    }


    public float GetNormalisedTime()
    {
        return _currentBehaviour.GetNormalisedTime();
    }
}
