using UnityEngine;

namespace mgaia.tk2d
{
    /// <summary>
    /// Behaviour utilizado para atualizar as cores de uma tk2dBaseSprite em conjunto com um animator da Unity
    /// </summary>
    [RequireComponent(typeof(tk2dBaseSprite))]
    [ExecuteInEditMode]
    [DisallowMultipleComponent]
    public class Tk2dSpriteColorAdapter : MonoBehaviour
    {
        private const string UPDATE_COLORS_METHOD_NAME = "UpdateColors";

        private tk2dBaseSprite mBaseSprite;
        private Color mOldColor;
        private Color mInitialColor;

        private void Awake()
        {
            mBaseSprite = GetComponent<tk2dBaseSprite>();
            mInitialColor = mBaseSprite.color;
        }

        private void OnStartAnimation()
        {
            mBaseSprite.color = mInitialColor;

            UpdateColor();
        }

        private void Update()
        {
            if (!mOldColor.Equals(mBaseSprite.color))
            {
                UpdateColor();
            }
        }

        private void UpdateColor()
        {
            mOldColor = mBaseSprite.color;

            mBaseSprite.SendMessage(UPDATE_COLORS_METHOD_NAME, SendMessageOptions.RequireReceiver);
        }
    }
}