using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class Teacher : MonoBehaviour
{
	public int 			m_Speed = 50;
	public Vector3 		m_Target;
	public bool 		m_IsMoving;
	
	public int			m_Pos;
	
	//Animation
	public List<Material> m_Materials;
	private float m_AnimTimer; //1 loop per second
	private float m_TimePerFrame = 0.20f;
	
	// Use this for initialization
	void Start () 
	{
		m_Speed = Random.Range(40,80); 
		
		//Let's be a random character
		int matId = Random.Range (0, m_Materials.Count);
		gameObject.GetComponent<MeshRenderer>().material = m_Materials[matId];
		
		m_Pos = 0;
		//Create random target
		m_Target = CreateRandomTarget();
	}
	
	void OnDestroy()
	{
		
	}
	
	// Update is called once per frame
	private void Update () 
	{
		Move();
		HandleAnimtion();
	}
	
	private void Move()
	{
		gameObject.GetComponent<Rigidbody>().velocity = new Vector3(0,0,0);
		
		//move unit
		if (m_IsMoving)
		{
			Vector3 velocity, direction;
			direction = m_Target - transform.position;
			direction.Normalize();
			velocity = direction * m_Speed * Time.deltaTime;
		
			transform.position += velocity;
		
			//Make our character look at the direction he is walking in
			transform.LookAt(m_Target);
			
			//ShouldIStop();
			
			if(IsAtTarget())
				m_Target = CreateRandomTarget();
		}
	}
	
	private bool IsAtTarget()
	{
		if(Vector3.Distance(transform.position,m_Target) < 2)
		{
			return true;
		}
		return false;
	}
	
	public Vector3 CreateRandomTarget()
	{
		//calculate random position in safe zone
		Vector3 newPos = GameObject.FindGameObjectWithTag("SafeZone").transform.position;
		newPos -= new Vector3(30,0,30);
		if(m_Pos == 1)
		{
			newPos += new Vector3(0,0,60);
			m_Pos++;
		}
		else if(m_Pos == 2)
		{
			newPos += new Vector3(60,0,60);
			m_Pos++;
		}
		else if(m_Pos == 3)
		{
			newPos += new Vector3(60,0,0);
			m_Pos=0;
		}else if(m_Pos==0)
		{
			m_Pos = 1;	
		}
		newPos.y = transform.position.y;
		return newPos;
	}
	
	private void HandleAnimtion()
	{
		//Check if we are not moving, in that case reset the offset
		if (!m_IsMoving)
		{
			renderer.material.SetTextureOffset("_MainTex", new Vector2(0.0f, 0.0f));
			return;
		}
		
		//Increase the animation timer
		m_AnimTimer += Time.deltaTime;
		
		//Once we have to swap frame
		if (m_AnimTimer >= m_TimePerFrame)
		{
			//Get the x offset of the texture & increase it
			float offset = renderer.material.GetTextureOffset("_MainTex").x;
			offset += 0.25f;
			if (offset >= 1.0f) offset = 0.0f;
			
			//Set the new offset
			renderer.material.SetTextureOffset("_MainTex", new Vector2(offset, 0.0f));
			
			//Reset timer
			m_AnimTimer = 0.0f;
		}
	}	
}