using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class Portal : MonoBehaviour {

	public GameObject[] soulPrefabs;

	public float cooldownRate = 3f;
	float cooldown = 1;

	public float hps = 100f;

	Text portalHPLabel;

	public Text[] chatboxes;

	int maxSpawnIndex = 0;
	float maxIndexCooldown = 10f;




	// Use this for initialization
	void Start () {
		portalHPLabel = GameObject.Find ("Portal HPs").GetComponent<Text>();

		foreach(Text t in chatboxes) {
			t.text = "";
		}
	}

	// Update is called once per frame
	void Update () {
		cooldown -= Time.deltaTime * (1f + StatManager.current.bonusPortalSpeed);

		UpdateMaxSpawnIndex();

		if(cooldown <= 0) {
			cooldown = cooldownRate;

			int circleIndex = Random.Range(0, maxSpawnIndex+1);

/*			float r = Random.Range(0f, 1f);

			if(r < 0.4f) {
				circleIndex = 0;
			}
			else if(r < 0.7f) {
				circleIndex = Random.Range (0,3);
			}
			else if(r < 0.9f) {
				circleIndex = Random.Range (0,6);
			}
			else {
				circleIndex = Random.Range (0,9);
			}
*/
			Instantiate(soulPrefabs[circleIndex], this.transform.position, Quaternion.identity);

			AddText("Level "+ (circleIndex+1) +" Sinner <b>"+ GetName() +"</b> has arrived.");
		}

		portalHPLabel.text = "Portal Health: " + Mathf.FloorToInt(hps) + "%";
		if(hps <= 0) {
			Game.current.Game_Lost();
		}

		hps =  Mathf.Min (100f, hps + (Time.deltaTime * StatManager.current.portalRegen / 10f) );

	}

	void UpdateMaxSpawnIndex() {
		maxIndexCooldown -= Time.deltaTime;

		if(maxIndexCooldown <= 0) {
			maxIndexCooldown = 15f;
			maxSpawnIndex = Mathf.Clamp(maxSpawnIndex+1, 0, 8);
		}
	}

	string GetName() {
		return SubscriberNames.names[ Random.Range(0, SubscriberNames.names.Length) ];
	}

	void AddText(string s) {
		for (int i = 0; i < 4; i++) {
			chatboxes[i].text = chatboxes[i+1].text;
		}
		chatboxes[4].text = s;
	}

	void OnMouseDown() {
		cooldown -= 0.50f;
	}

}
