using UnityEngine;
using System.Collections;

public class VendingMachine : MonoBehaviour {
	public float m_DetonateTimer = 5.0f;
	private float m_Timer;
	private bool m_HeroInRange;
	
	//Animation
	private float m_AnimTimer; //1 loop per second
	private float m_TimePerFrame = 0.05f;
	private bool m_Exploding = false;
	
	// Use this for initialization
	void Start () 
	{
		m_AnimTimer = 0;
		m_HeroInRange = false;
		m_Timer = 0;
	}
	
	// Update is called once per frame
	void Update () 
	{
		Tick();
		
		if(m_Exploding)
			HandleAnimation();
	}
	
	void Tick()
	{
		if(m_HeroInRange)
		{
			m_Timer += Time.deltaTime;
			if(m_Timer >= m_DetonateTimer && m_Exploding==false)
			{
				Explode();
			}
		}
	}
	
	void Explode()
	{
		//lock hero in place
		Hero hero = GameObject.FindGameObjectWithTag("Hero").GetComponent<Hero>();
		hero.m_Speed = 0;
		m_Exploding = true;
	}
	
	void HandleAnimation()
	{
		//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 += 1.0f/7;
			if (offset >= 1.0f)
			{
				if(GameObject.FindGameObjectWithTag("Hero")!=null)
					GameObject.FindGameObjectWithTag("Hero").GetComponent<Hero>().DestroyMe();
				offset = 1.0f-(1.0f/7);
			}
			
			//Set the new offset
			renderer.material.SetTextureOffset("_MainTex", new Vector2(offset, 0.0f));
			
			//Reset timer
			m_AnimTimer = 0.0f;
		}
		
	}
	
	void OnTriggerEnter(Collider coll)
	{
		if(coll.gameObject.tag=="Hero")
		{
			m_HeroInRange = true;	
			m_Timer = 0;	
		}
	}
	
	void OnTriggerExit(Collider coll)
	{
		if(coll.gameObject.tag=="Hero")
		{
			m_HeroInRange = false;
		}
	}
}
