using UnityEngine;
using System.Collections;

public class JumpScareController : MonoBehaviour
{
		private float lastJumpScare;
		private bool wasScared;
		private float nextInterval;
		public GameObject[] jumpScarePrefabs;
		private GameObject[] jumpScares;
		private bool isDebug;
		
		public AudioClip clip;

		void Start ()
		{
				jumpScares = new GameObject[jumpScarePrefabs.Length];
		}

		private Player getPlayer ()
		{
				return gameObject.GetComponent ("Player") as Player;
		}
		
	
		private void PlayClip (AudioClip audio)
		{
				if (audio != null)
						gameObject.audio.PlayOneShot (audio);
				else
						gameObject.audio.Stop ();
		}
	
	
		private void DoJumpScare ()
		{
				lastJumpScare = Time.time;
				PlayClip (clip);
				
				Debug.Log ("JumpScare");
				
				int index = Mathf.FloorToInt (jumpScares.Length * UnityEngine.Random.value);
				if (index >= jumpScares.Length)
						index = jumpScares.Length - 1;
				if (jumpScares [index] == null)
						jumpScares [index] = (GameObject)GameObject.Instantiate (jumpScarePrefabs [index]);
				
				((GUITexture)(jumpScares [index].guiTexture)).pixelInset = new Rect (-Screen.width / 2, -Screen.height / 2, Screen.width, Screen.height);
				jumpScares [index].SetActive (true);
		}
		private void Reset ()
		{
				foreach (var j in jumpScares)
						if (j != null)
								j.SetActive (false);

				isDebug = false;
		}

		void Update ()
		{
				var isScared = getPlayer ().Scared;
				
				if (Input.GetKeyDown (KeyCode.J)) {
						DoJumpScare ();
						isDebug = true;
				}
				
				if ((Time.time - lastJumpScare) >= .3f)
						Reset ();
		
				if (!isScared) {
						wasScared = false;
						if (!isDebug)
								Reset ();
						return;
				}
				
				if (!wasScared) {
						lastJumpScare = Time.time;
						nextInterval = 10.0f + 20.0f * UnityEngine.Random.value;
						wasScared = true;
						return;
				}
				
				if ((Time.time - lastJumpScare) >= nextInterval) {
						DoJumpScare ();
						
						nextInterval = 50.0f + 60.0f * UnityEngine.Random.value;
				}
		}
}
