using UnityEngine;
using System.Collections;

public class ShadeScript : MonoBehaviour {

	public PlayerScript ps;
	public int shadetime = 0;
	public bool whileawake = false;
	public int shadeanim = 0;
	public SpriteRenderer sr;
	public MiasmaScript ms;

	// Use this for initialization
	void Start () {
		ps = GameObject.FindGameObjectWithTag ("Player").GetComponent<PlayerScript>();
		sr = GetComponentInChildren<SpriteRenderer>();
	}
	
	// FixedUpdate
	void FixedUpdate () {
		bool beingdestroyed = false;
		shadeanim++;
		if (shadeanim == 10) {
			sr.sprite = ps.shade2;
		} else if (shadeanim >= 20) {
			shadeanim = 0;
			sr.sprite = ps.shade1;
		}
		shadetime++;
		if ((shadetime >= 300) || (ps.transition) || (ps.haswon)) {
			beingdestroyed = true;
			if (((ps.transition) && (!ps.isdreaming)) || (shadetime >= 300)) {
				Instantiate (ps.poof,new Vector3(transform.position.x,transform.position.y,-4F),Quaternion.identity);
			}
		}
		if (!beingdestroyed) {
			if ((!ps.gameover) && (!ps.ishurt)) {
				Vector3 newmove = (ps.transform.position - transform.position);
				newmove.Normalize ();
				transform.Translate (new Vector3((newmove.x * 0.035F),(newmove.y * 0.035F),newmove.z * 0.035F));
				if (Vector3.Distance (ps.transform.position,transform.position) < 0.75F) {
					ps.ishurt = true;
					AudioSource.PlayClipAtPoint (ps.sfx[(int)((Random.value * 5F) + 9)],transform.position);
				}
				if (ps.transform.position.x < transform.position.x) {
					sr.transform.localScale = new Vector3(-4F,4F,1);
				} else {
					sr.transform.localScale = new Vector3(4F,4F,1);
				}
			}
		} else {
			ms.shadeout = false;
			DestroyObject (gameObject);
		}
	}
}
