using UnityEngine;
using System.Collections;

public class MiasmaScript : MonoBehaviour {

	public PlayerScript ps;
	public bool retained = false;
	public int spawncountdown = -1;
	public bool shadeout = false;

	// Use this for initialization
	void Start () {
		ps = GameObject.FindGameObjectWithTag ("Player").GetComponent<PlayerScript>();
	}
	
	// Update is called once per frame
	void Update () {
		if (spawncountdown < 0) {
			spawncountdown = (int)((Random.value * 250F) + 50F);
		} else if ((!shadeout) && (Vector3.Distance (transform.position,ps.transform.position) < 5F)) {
			spawncountdown--;
			if (spawncountdown <= 0) {
				spawncountdown = (int)((Random.value * 250F) + 50F);
				if (Random.value < ps.stress) {
					GameObject newshade = Instantiate (ps.shade,transform.position,Quaternion.identity) as GameObject;
					newshade.GetComponent<ShadeScript>().ms = this;
					shadeout = true;
					AudioSource.PlayClipAtPoint (ps.sfx[(int)((Random.value * 8F) + 1)],transform.position);
				}
			}
		}
		if ((Vector3.Distance (transform.position,ps.transform.position) < 1.1F) && (!ps.ishurt)) {
			ps.ishurt = true;
			AudioSource.PlayClipAtPoint (ps.sfx[(int)((Random.value * 5F) + 9)],transform.position);
		}
		if ((ps.transition) && (!retained)) {
			if (ps.stress < 1F) {
				DestroyObject (gameObject);
			} else {
				retained = true;
			}
		} else if ((!ps.isdreaming) && (ps.transition) && (retained)) {
			Instantiate (ps.poof,new Vector3(transform.position.x,transform.position.y,-4F),Quaternion.identity);
			DestroyObject (gameObject);
		}
	}
}
