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

public class HeadExplosionBehaviour : MonoBehaviour
{
	public GameObject m_BloodEmitter;
	
	private float m_Timer = 0;
	private int m_CurrentFrame = 0;
	private float m_TimePerFrame = 0.15f;
	
	private int m_ShakeDirection = -1;
	
	// Use this for initialization
	void Start ()
	{
		//Move the y higher to make sure no one walks over it
		Vector3 pos = transform.position;
		pos.y = 100;
		transform.position = pos;
	
	}
	
	// Update is called once per frame
	void Update ()
	{
		//Increase the animation timer
		m_Timer += Time.deltaTime;
		
		HandleHeadExplosion();
		
		//Dissable sphere collider again
		if(m_Timer>0.1f && m_CurrentFrame==6)
		{
			gameObject.GetComponent<SphereCollider>().enabled = false;	
		}
	}
	
	private void HandleHeadExplosion()
	{

		//We don't have to animate the explosion anymore after we reached the last frame
		if (m_CurrentFrame >= 6) return;
		Shake();
		//Once we have to swap frame
		if (m_Timer >= m_TimePerFrame)
		{
			//Get the x offset of the texture & increase it
			float offset = m_CurrentFrame * 0.16666666f; //6 frames
			++m_CurrentFrame;
			
			//Set the new offset
			renderer.material.SetTextureOffset("_MainTex", new Vector2(offset, 0.0f));
			
			//Make the last frame a slow mo-shot (because fuck yeah)
			if (m_CurrentFrame == 5) m_TimePerFrame *= 3;
			
			//Check if we reached the 5th frame (last anim frame)
			if (m_CurrentFrame == 6)
			{
				//Move the y lower to make sure the next head will be above the corpse
				Vector3 pos = transform.position;
				pos.y = 4;
				transform.position = pos;
				pos.y = 3;
				Instantiate(m_BloodEmitter, pos, transform.rotation); //RAINING BLOOD
				//enable spehere collider for kill trigger
				gameObject.GetComponent<SphereCollider>().enabled = true;
			}
			//Reset timer
			m_Timer = 0.0f;
		}
	}
	
	private void Shake()
	{
		Vector3 movement = new Vector3();
		movement.x = 2 * m_ShakeDirection;
		movement.y = 0;
		movement.z = 2 * m_ShakeDirection;
		
		transform.position += movement;
		m_ShakeDirection *= -1;
	}
	
	void OnTriggerEnter(Collider coll)
	{
		if(coll.gameObject.GetComponent<Hero>()!=null)
		{
			coll.gameObject.GetComponent<Hero>().DestroyMe();			
		}
		if(coll.gameObject.tag == "Unit")
		{
			Instantiate(m_BloodEmitter, coll.gameObject.transform.position, coll.gameObject.transform.rotation); //RAINING BLOOD
			Destroy(coll.gameObject);
		}
	}
	
	public void Scream(List<AudioClip> sounds)
	{
		AudioSource sound = gameObject.AddComponent<AudioSource>();
		sound.clip = sounds[Random.Range(0,sounds.Count)];
		sound.Play();	
	}
}
