using UnityEngine;
using System.Collections;

public class Actor : MonoBehaviour {

	public string Name;
	
	public Anim[] anims;
	
	public string currentAnimName;
	
	private Anim currentAnim;
	
	private int animIndex = 0;
	private float intervalTimer = 0;
	
	private bool allowedToMove = true;
	private float moveTime = 0;
	private bool turn;
	private string callBackAnim;
	
	void Update ()
	{
		UpdateAnim();
	}
	
	void Start ()
	{
		setCurrentAnim(currentAnimName);
	}
	
	public void setCurrentAnim (string animName)
	{
		if (anims.Length == 0)
			return;
		
		for (int a = 0; a < anims.Length; a++)
			if (anims[a].Name == animName)
				currentAnim = anims[a];
	}
	
	void UpdateAnim ()
	{
		if (currentAnim == null || currentAnim.frame.Length == 0)
			return;
		
		intervalTimer += Time.deltaTime;
		if (intervalTimer > currentAnim.interval)
		{
			intervalTimer = 0;
			animIndex++;
			if (animIndex >= currentAnim.frame.Length)
				animIndex = 0;
			ChangeImage();
		}
	}
	
	void ChangeImage ()
	{
		if (currentAnim.frame[animIndex] != null)
			renderer.material.mainTexture = currentAnim.frame[animIndex];
	}
	
	public void MoveTo (Transform target, float time, bool Turn, string callBack)
	{
		moveTime = time;
		turn = Turn;
		StartCoroutine("moveTo", target);
		callBackAnim = callBack;
	}
	
	IEnumerator moveTo (Transform target)
	{
		Vector3 startPos = transform.position;
		float timeTaken = 0;
		while (timeTaken < moveTime)
		{
			timeTaken += Time.deltaTime;
			transform.position = Vector3.Lerp(startPos, target.position, timeTaken / moveTime);
			yield return null;
		}
		transform.position = target.position;
		transform.rotation = target.rotation;
		if (turn)
		{
			Vector3 newScale = transform.localScale;
			newScale.x *= -1;	
			transform.localScale = newScale;
		}
		moveTime = 0;
		setCurrentAnim(callBackAnim);
	}
}

[System.Serializable]
public class Anim
{
	public string Name;
	public float interval = 0.5f;
	public Texture2D[] frame;
}

