using UnityEngine;
using System.Collections;

public class TreeHealth : MonoBehaviour {

	private float treeHealth = 10.0f;
	private GameObject tree;
	private GameObject stump;
	private ParticleSystem TreeExp;

	public GameObject rigid;

	private bool dead = false;
		
	//DEBUG
	public bool treeDeadOnStart = false;

	// Use this for initialization
	void Start () {
		treeHealth = 10.0f;

		//tree = GameObject.findChild("tree01_tree");
		tree = this.transform.GetChild(0).gameObject;
		//stump = GameObject.findChild("tree01_stump");
		stump = this.transform.GetChild(1).gameObject;
		TreeExp = this.particleSystem;

		tree.active = true;
		stump.active = false;

		dead = false;
	}
	
	// Update is called once per frame
	void LateUpdate () {
		//DEBUG

		if(treeDeadOnStart && !dead) {
			Debug.Log ("You're killing me!");
			treeHealth = -0.1f;
			Debug.Log(treeHealth);
		}

		if(treeHealth < 0 && !dead) {
			GameObject go = GameObject.Find("GUItext");
			GUItext other = (GUItext) go.GetComponent(typeof(GUItext));
			other.AddScore();

			//Destroy(this);
			Debug.Log("died");
			tree.active = false;
			stump.active = true;

			int RandomEvent = Random.Range(1,50);
//			other.RandomNum = RandomEvent;
			float vecX = 0f;
			float vecY = 0f;
			float vecZ = 0f;

			if(RandomEvent<20) {
				vecY = 5.0f;
			} else if(RandomEvent<40) {
				vecY = 2.0f;
				vecX = 4.0f;
			} else if(RandomEvent<50) {
				TreeExp.Play ();
				vecY = 2.0f;
			}
				  
			Instantiate(rigid, this.transform.position + new Vector3(vecX,vecY,vecZ), this.transform.rotation);
			dead = true;


		}
	}

	public void hitTree() {
		float randomValue = Random.Range(2,6);
		treeHealth = treeHealth - randomValue;
	}
//	public void TreeEffect() {
//		Instantiate(
//	}
}
