using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class Alchemy : MonoBehaviour {
	private float idle;

	public GameObject Ruby;
	public GameObject Diamond;
	public GameObject Saphire;
	public GameObject Emerald;
	public GameObject Topaz;

	static private List<GameObject> list = new List<GameObject>();
	void Awake () {
		list.Add(gameObject);
	}
		
	void Update () {
		idle += 1f;


		foreach (var itemA in list) {

			foreach (var itemB in list) {
				if (itemA == itemB)
					continue;
				if (itemA.name == itemB.name)
				{
					continue;
				}
					float dist = Vector3.Distance (itemA.transform.position, itemB.transform.position);
					if (dist < 0.6f) {
					Vector3 p0 = itemA.transform.position;
					Vector3 p1 = itemB.transform.position;
					float z = 0.98f;
					float c = 0.02f;
					itemA.transform.position = new Vector3 (p0.x * z + p1.x * c, p0.y * z + p1.y * c, p0.z * z + p1.z * c);
					itemB.transform.position = new Vector3 (p1.x * z + p0.x * c, p1.y * z + p0.y * c, p1.z * z + p0.z * c);


					}
				}
			}


		foreach (var itemA in list) {
			Alchemy c2 = itemA.GetComponent<Alchemy> ();
			if (c2.idle < 120f) {
				continue;
			}
			List<GameObject> deletelist = new List<GameObject>();
			int[] a = new int[5]; 
			deletelist.Add (itemA);
			a [GetTypeNumber (itemA.name)] += 1;
			foreach (var itemB in list) {
				if (itemA == itemB)
				continue;
				Alchemy c = itemB.GetComponent<Alchemy> ();



				if (c.idle < 120f) {
					continue;
				}



				float dist = Vector3.Distance (itemA.transform.position, itemB.transform.position);
				if (dist < 0.6f) {
					a [GetTypeNumber (itemB.name)] += 1;
					deletelist.Add (itemB);


					if (a [0] > 0 && a [1] > 0) {
						WallsManager.allHeaven = true;
						foreach (var i in deletelist) {
							Destroy (i);
						}
						return;
					}


			
					if (a [1] > 0 && a [3] > 0) {
						foreach (var i in deletelist) {
							Destroy (i);
						}
						GameObject s = Instantiate ( Emerald,itemA.gameObject.transform.position, new Quaternion ()) as GameObject ;
						s.name = "Emerald";
						PowerUpLower z = s.GetComponent<PowerUpLower>();
						z.enabled = false;
						return;
					}

					if (a [2] > 0 && a [4] > 0) {
						foreach (var i in deletelist) {
							Destroy (i);
						}
						WallsManager.allHeaven = true;
						return;
					}
				}
			}
		}
	}

	void OnDestroy()
	{
		list.Remove (gameObject);
	}

	private int GetTypeNumber(string type){
		switch (type) {
		case "Ruby":
			return 0;
		case "Saphire":
			return 1;
		case "Emerald":
			return 2;
		case "Topaz":
			return 3;
		case "Diamond":
			return 4;	
		}

		throw new UnityException ("Item with type: '" + type + "' is not supported.");
	} 
}
