using UnityEngine;
using System.Collections;

[RequireComponent(typeof(AnimationManager))]
public class TowerPiece : MonoBehaviour
{
    public float height = 1.1f;

    private AnimationManager _animationManager;
    private bool _isFalling;
    private Vector3 _fallingInitialPosition;
    private Vector3 _fallingTargetPosition;

    public enum State
    {
        Idle,
        Dying,
        Dead,
        Falling,
    }

    void Awake()
    {
        _animationManager = GetComponent<AnimationManager>();
    }

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

    // Update is called once per frame
    void Update()
    {
        if (_isFalling)
        {
            //Debug.Log("IsFalling -> StateHash = " + Animator.StringToHash(State.Falling.ToString()) + " behaviour previous state = " + _behaviour.GetPreviousStateHash());

            if (_animationManager.IsStateActive((int)State.Falling))
            {
                float easeInDelta = _animationManager.GetNormalisedTime();
                easeInDelta *= easeInDelta * easeInDelta;
                transform.localPosition = Vector3.Lerp(_fallingInitialPosition, _fallingTargetPosition, easeInDelta);
            }
            else
            {
                transform.localPosition = _fallingTargetPosition;
                _isFalling = false;
            }
        }
    }

    public void SetState(State state)
    {
        _animationManager.SetState((int)state);
    }

    public void StartFalling(Vector3 targetPosition)
    {
        SetState(State.Falling);
        _isFalling = true;
        _fallingInitialPosition = transform.localPosition;
        _fallingTargetPosition = targetPosition;
    }
}
