using UnityEngine;
using System.Collections;
using UnityEngine.UI;

namespace uTools
{
    public class uTweenSprite : uTweenValue
    {
        public enum SpriteType
        {
            SpriteRenderer,
            Image,
        }

        public SpriteType spriteType;

        public Sprite[] sprites;

        SpriteRenderer m_spriteRenderer;

        SpriteRenderer SpriteRenderer
        {
            get
            {
                if (null == m_spriteRenderer)
                {
                    m_spriteRenderer = GetComponent<SpriteRenderer>();
                }
                return m_spriteRenderer;
            }
        }

        Image m_image;

        Image Image
        {
            get
            {
                if (null == m_image)
                {
                    m_image = GetComponent<Image>();
                }
                return m_image;
            }
        }

        void Awake()
        {
            if (spriteType == SpriteType.SpriteRenderer)
            {
                m_spriteRenderer = GetComponent<SpriteRenderer>();
            }
            else
            {
                m_image = GetComponent<Image>();
            }            
        }

        int currentIndex = -1;

        protected override void ValueUpdate(float value, bool isFinished)
        {
            int index = Mathf.FloorToInt(value);
            int length = sprites.Length;
            if (index >= length) index = length - 1;
            if (index <= 0) index = 0;
            if (currentIndex != index)
            {
                if (spriteType == SpriteType.SpriteRenderer)
                {
                    SpriteRenderer.sprite = sprites[index];
                }
                else
                {
                    Image.sprite = sprites[index];
                    Image.SetNativeSize();
                }
                currentIndex = index;
            }
        }
    }
}
