using UnityEngine;
using System.Collections;

public class Soul : MonoBehaviour {

	public int circleNumber = 1;

	SoulChamber myChamber;

	float speed = 2f;

	float lifeSpan = 10f;
	Vector2 wanderDir;

	Transform questionMark;

	public GameObject deathPrefab;

	// Use this for initialization
	void Start () {
		wanderDir = Random.insideUnitCircle.normalized;

		questionMark = transform.Find("?");
		questionMark.gameObject.SetActive(false);
	}
	
	// Update is called once per frame
	void Update () {
		if(myChamber != null && myChamber.numSouls >= myChamber.capacity)
			myChamber = null;

		if(myChamber == null)
			FindSoulChamber();

		if(myChamber != null) {
			questionMark.gameObject.SetActive(false);
			MoveToSoulChamber();
		}
		else {
			// Wander
			questionMark.gameObject.SetActive(true);
			lifeSpan -= Time.deltaTime;
			if(lifeSpan < 0) {
				Poof ();
				return;
			}
			this.transform.Translate(wanderDir/3f * Time.deltaTime);

		}
	}

	void Poof() {
		SoundManager.current.PlaySound("Soul Fail");
		Instantiate(deathPrefab, transform.position, Quaternion.Euler(0, 0, Random.Range(0, 360)) );
		Destroy(gameObject);
	}

	void FindSoulChamber() {
		if(myChamber != null) {
			return;
		}

		if(SoulChamber.chambers==null || SoulChamber.chambers.ContainsKey(circleNumber) == false) {
			return;
		}

		float dist = Mathf.Infinity;

		foreach(SoulChamber sc in SoulChamber.chambers[circleNumber]) {
			float d = Vector2.Distance(sc.transform.position, this.transform.position);

			if( sc.numSouls < sc.capacity && (myChamber==null || d < dist) ) {
				myChamber = sc;
				dist = d;
			}
		}
	}

	void MoveToSoulChamber() {
		if(myChamber == null) {
			return;
		}

		Vector2 dir = myChamber.transform.position - this.transform.position;

		if(dir.magnitude <= 0.5f) {
			myChamber.numSouls++;
			SoundManager.current.PlaySound("Soul Pop");
			Destroy(gameObject);
		}
		else {
			this.transform.Translate( dir.normalized * speed * Time.deltaTime );
		}
	}

}
