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

public class Hero : MonoBehaviour
{
	//Datamembers
	public float m_Speed = 100;
	public float m_Friction = 5;
	private float m_Rotation;
	
	private Vector3 m_Direction;
	private Vector3 m_Velocity;
	
	public GameObject m_HeroExplosion;
	
	//Animation
	public List<Material> m_Materials;
	float m_AnimTimer; //1 loop per second
	float m_TimePerFrame = 0.20f;
	
	// Use this for initialization
	public void Start ()
	{
		//Let's be a random character
		int matId = Random.Range (0, m_Materials.Count - 1);
		gameObject.GetComponent<MeshRenderer>().material = m_Materials[matId];
	}
	
	// Update is called once per frame
	public void Update ()
	{
		gameObject.GetComponent<Rigidbody>().velocity = new Vector3(0, 0, 0);
			
		HandleInput();
		Move();
		HandleAnimation();
	}
	
	private void HandleInput()
	{
		//Verticaal bewegen
		if (Input.GetButton ("Horizontal"))
		{
			m_Direction.x = Input.GetAxis("Horizontal");
			m_Velocity.x = m_Speed * Time.deltaTime;
		}
		else
		{
			m_Velocity.x -= m_Friction * Time.deltaTime;
			m_Direction.x = 0;
		}
		
		//Horizontaal bewegen
		if (Input.GetButton ("Vertical"))
		{
			m_Direction.z = Input.GetAxis("Vertical");
			m_Velocity.z = m_Speed * Time.deltaTime;
		}
		else
		{
			m_Velocity.z -= m_Friction * Time.deltaTime;
			m_Direction.z = 0;
		}
		
		//Don't go below 0 faggot!
		if (m_Velocity.x <= 0) m_Velocity.x = 0;
		if (m_Velocity.z <= 0) m_Velocity.z = 0;
	}
	
	private void Move()
	{
		Vector3 movement;
		movement.x = m_Direction.x * m_Velocity.x;
		movement.y = 0;
		movement.z = m_Direction.z * m_Velocity.z;
		
		transform.position += movement;
		
		transform.LookAt(transform.position + m_Direction);
		
	}
	
	private void HandleAnimation()
	{
		//Check if we are not moving, in that case reset the offset
		if (m_Direction.x == 0 && m_Direction.z == 0)
		{
			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;
		}
	}	
	
	public void DestroyMe()
	{
		GameObject ui = GameObject.Find("Interface");
		ui.GetComponent<Interface>().SetMenuState(2);
		Instantiate(m_HeroExplosion,transform.position,transform.rotation);	
		Destroy(gameObject);
		gameObject.GetComponent<Collider>().enabled = false;
	}
}