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

public class ProgramBehavior : MonoBehaviour {

	private const float symbolOffset = 0.375f;
	public Canvas bubble;
	public bool accessGranted = false;
    public AudioClip enterShieldSound;
    public AudioClip nirvanaSound;
    public AudioClip bulletExplosionSound;
    public AudioClip programTalkingSound;

	public int programType;
	private bool isVirus = false;
	private string greeting;
	private bool inNirvana = false;
	private bool deadByShield = false;
	private bool deadByBullet = false;

	private bool lerpDeath = false;
	private float lerpTime = 1f;
	private float currentLerpTime;
	private float startAlpha = 1f;
	private float endAlpha = 0;
	private Vector3 startSize;
	private Vector3 endSize;

	// Use this for initialization
	void Start () {

		startSize = gameObject.transform.localScale;
		float randSize = Random.Range(1.1f, 1.5f);
		endSize = startSize * randSize;

		Quaternion bubbleRot = GetComponentInChildren<RectTransform>().localRotation;
		bubbleRot.z = -transform.localRotation.z;
		GetComponentInChildren<RectTransform>().localRotation = bubbleRot;

		programType = Random.Range(0, 6);
		isVirus = Random.Range(0, 2) == 0;
		accessGranted = isVirus;
		greeting = isVirus ? Dictionaries.dictionaries.encyclopedia[programType].greetingsKO[Random.Range(0, Dictionaries.dictionaries.encyclopedia[programType].greetingsKO.Length)] : 
			Dictionaries.dictionaries.encyclopedia[programType].greetingsOK[Random.Range(0, Dictionaries.dictionaries.encyclopedia[programType].greetingsOK.Length)];

		for(int i = 0; i < greeting.Length; i++)
		{
			GameObject symbol = Instantiate(Resources.Load("Prefabs/symbol", typeof(GameObject)), bubble.transform.position + 
			                                new Vector3 (-(greeting.Length -1)* symbolOffset/2 + symbolOffset*i,0,0), Quaternion.identity) as GameObject;
			symbol.transform.parent = bubble.transform;
			symbol.gameObject.GetComponent<SpriteRenderer>().sprite = Resources.Load<Sprite>("Symbols/bubble_" + programType + greeting[i]);
			//symbol.transform.localScale *= 1.1f;
		}

		bubble.gameObject.SetActive(false);

		Vector3 pos = transform.position;
		pos.z = pos.y * 0.1f;
		transform.position = pos;
	}
	
	// Update is called once per frame
	void Update () {



		if (lerpDeath)
		{
			currentLerpTime += Time.deltaTime;
			if (currentLerpTime > lerpTime)
			{
				currentLerpTime = lerpTime;
			}

			float perc = currentLerpTime / lerpTime;
			Color col = gameObject.GetComponent<SpriteRenderer>().color;
			col.a = Mathf.Lerp(startAlpha,endAlpha,perc);
			gameObject.GetComponent<SpriteRenderer>().color = col;

			Vector3 vect = Vector3.Lerp(startSize, endSize, perc);
			gameObject.transform.localScale = vect;

			if (col.a == endAlpha)
			{
				Destroy(gameObject);
			}
		}
	
	}

	void OnTriggerEnter2D (Collider2D collider)
	{
		if (collider.tag == "shield")
		{
			if (!accessGranted && !deadByBullet)
			{
				deadByShield = true;
				StartCoroutine(CreateShieldExplosion(gameObject, 1f));
				gameObject.GetComponent<SpriteRenderer>().enabled = false;
                GetComponent<AudioSource>().PlayOneShot(bulletExplosionSound);

                //				Destroy(gameObject);

				Dictionaries.dictionaries.score --;
            }
            else
	        {
	            GetComponent<AudioSource>().PlayOneShot(enterShieldSound);
				inNirvana = true;
				bubble.GetComponent<Canvas>().enabled = false;
			}
		}
		else if (collider.tag == "bullet")
		{
			if (!inNirvana && !deadByShield)
			{
				deadByBullet = true;
	            GetComponent<AudioSource>().PlayOneShot(bulletExplosionSound);
	            StartCoroutine(CreateDestroyExplosion(collider.gameObject, 1f));
				Destroy(collider.gameObject);
				Dictionaries.dictionaries.bulletExists = false;
				gameObject.GetComponent<SpriteRenderer>().enabled = false;

				if (isVirus)
				{
					Dictionaries.dictionaries.score ++;
				}
				else
				{
					Dictionaries.dictionaries.score --;

				}
			}
		}
		else if (collider.tag == "nirvana")
		{
            //			gameObject.GetComponent<Rigidbody2D>().velocity = Vector3.zero;

            GetComponent<AudioSource>().PlayOneShot(nirvanaSound);

            lerpDeath = true;

			if (!isVirus)
			{
				Dictionaries.dictionaries.score ++;
			}
			else
			{
				Dictionaries.dictionaries.gameOver = true;
			}

		}


    }

	void OnMouseDown()
	{
        Dictionaries.dictionaries.activeProgram = gameObject;

		GameObject[] programs = GameObject.FindGameObjectsWithTag("program");

		foreach(GameObject program in programs)
		{
			if(program != gameObject && !program.GetComponent<ProgramBehavior>().deadByBullet && !program.GetComponent<ProgramBehavior>().deadByShield && program.GetComponent<ProgramBehavior>().inNirvana)
			{
				program.gameObject.GetComponent<ProgramBehavior>().bubble.gameObject.SetActive(false);
			}
		}

        if(!bubble.gameObject.activeSelf)
        {
            GetComponent<AudioSource>().PlayOneShot(programTalkingSound);
        }

        bubble.gameObject.SetActive(true);

	}

	public IEnumerator CreateDestroyExplosion (GameObject bullet, float time)
	{
		if (!isVirus) Dictionaries.dictionaries.killedGoodPrograms ++;
		Destroy(bubble.gameObject);
		GameObject bulletExplosion = Instantiate(Resources.Load("Prefabs/bulletExplosion", typeof(GameObject)), bullet.transform.position, Quaternion.identity) as GameObject;
		yield return new WaitForSeconds (time);
//		Debug.Log("Destroying Explosion!");
		Destroy (bulletExplosion);
		Destroy(gameObject);


	}
	public IEnumerator CreateShieldExplosion (GameObject bullet, float time)
	{
		if (!isVirus) Dictionaries.dictionaries.killedGoodPrograms ++;
		Destroy(bubble.gameObject);
		GameObject bulletExplosion = Instantiate(Resources.Load("Prefabs/programExplosion", typeof(GameObject)), bullet.transform.position, Quaternion.identity) as GameObject;
		yield return new WaitForSeconds (time);
		//		Debug.Log("Destroying Explosion!");
		Destroy (bulletExplosion);
		Destroy(gameObject);
		
	}
}
