using UnityEngine;
using System.Collections;

public class SpriteSheetIndexV : MonoBehaviour
{
    public float repeatX = 1;
    public int uvTieY = 1;
    public int index = 0;
    public bool enable = false;

    public float[] times;
    public int[] frames;
    public float length;
    public bool loop;

    private Vector2 _size;
    private Renderer _myRenderer;
    private int _lastIndex = -1;

    private float _framecount;

    void Start()
    {
        _size = new Vector2(repeatX, 1.0f / uvTieY);
        _myRenderer = GetComponent<Renderer>();
        if (_myRenderer == null)
            enabled = false;
        _framecount = 0;
        Update();
    }
    // Update is called once per frame
    void Update()
    {
        UpdateAnimation();

        _myRenderer.enabled = enable;
	    if(!enable)
	    {
		    return;
	    }
        // Calculate index
        if (index != _lastIndex)
        {
            // split into horizontal and vertical index
            int uIndex = 0;
            int vIndex = index % uvTieY;

            // build offset
            // v coordinate is the bottom of the image in opengl so we need to invert.
            Vector2 offset = new Vector2(uIndex * uvTieY, 1.0f - _size.y - vIndex * _size.y);

            _myRenderer.material.SetTextureOffset("_MainTex", offset);
            _myRenderer.material.SetTextureScale("_MainTex", _size);

            _lastIndex = index;
        }
    }

    void UpdateAnimation()
    {
        if (times.Length == 0) return;
        if (!loop && _framecount > length) return;
        _framecount += Time.deltaTime;
        _size = new Vector2(repeatX, 1.0f / uvTieY);
        if (_framecount > length)
        {
            _framecount -= length;
        }
        if (_framecount < 0 && loop)
        {
            _framecount = 0;
        }
        for (int i = times.Length-1; i >= 0; --i)
        {
            if(_framecount >= times[i])
            {
                if (frames[i] < 0)
                {
                    enable = false;
                }
                else
                {
                    enable = true;
                    index = frames[i];
                }
                return;
            }
        }
    }
	
	public void SetIndex(int i)
	{
		index = (int)i;
	}

    public void SetRepeat(float r)
    {
        repeatX = r;
    }
}