#pragma strict

class TxAnimator
{
	private var m_TXs:Texture2D[];
	private var m_nCnt:int			= 0;
	private var m_fCurTm:float		= 0;
	private var m_fDuration:float	= 0;
	private var m_fX:float			= 0;
	private var m_fY:float			= 0;
	private var m_fCX:float			= 0;
	private var m_fCY:float			= 0;
	private var m_bLoop:boolean		= false;
	private var m_bPlaying:boolean	= false;
	private var m_nTxIdx:int = 0;
	function TxAnimator(_txPrefix:String, _frmCnt:int, _tm:float, _loop_play:boolean)
	{
		m_nCnt		= _frmCnt;
		m_fDuration = _tm;
		m_bPlaying	= _loop_play;
		m_bLoop		= _loop_play;
		if (_loop_play)
			m_fCurTm = Random.Range(0, m_fDuration);
			
		m_TXs = new Texture2D[m_nCnt];
		for (var n:int = 0; n < m_nCnt; n ++)
		{
			var txName:String = _txPrefix + n.ToString("D2");
			m_TXs[n] = Resources.Load("Textures/" + txName, Texture2D);
			
			if (m_TXs[n] == null)
				Debug.Log("ERROR: no found ani texture:" + txName);
		}
	}
	
	// play once
	function Play()
	{
		m_bLoop		= false;
		m_bPlaying	= true;
		m_fCurTm	= 0;
	}
	//play looply
	function Play(play:boolean)
	{
		m_bLoop		= true;
		m_bPlaying	= play;
		m_fCurTm	= 0;
	}
	
	function SetPos(_x:float, _y:float)
	{
		m_fX = _x; 
		m_fY = _y;
	}
	
	function SetDrawSize(_cx:float, _cy:float)
	{
		m_fCX = _cx; 
		m_fCY = _cy;
	}
	
	function Update()
	{
		if (!m_bPlaying)
			return;
			
		m_fCurTm += Time.deltaTime;
		
		if (m_fCurTm > m_fDuration)
		{
			if (m_bLoop)
				m_fCurTm -= m_fDuration;
			else
				m_bPlaying = false;
		}
		
		m_nTxIdx = Mathf.FloorToInt(m_fCurTm / (m_fDuration/m_nCnt)) % m_nCnt;
	}
	
	function GetTexture():Texture2D
	{
		if (m_bPlaying)
			return m_TXs[m_nTxIdx];
			
		return null;
	}
	
	function OnGUI()
	{
		if (! m_bPlaying)
			return;
		
		if (m_fCX != 0 && m_fCY != 0)
			UIUtil.DrawTexAs4G(m_fX, m_fY, m_fCX, m_fCY, GetTexture());
		else
			UIUtil.DrawTexAs4G(m_fX, m_fY, GetTexture());
	}
}