using UnityEngine;
using System.Collections;

public class ProgramSpawner : MonoBehaviour {

	public GameObject destination;
	public float maxProgramSpeed = 0.5f;
	public float minProgramSpeed = 0.1f;
	public float minSpawnTime = 10.0f;
	public float maxSpawnTime = 25.0f;

	public GameObject core;

	private float nextSpawnTime = 0;
	private float lastSpawnTime = 0;

	private bool spawnCore = false;
	private Vector3 coreStartSize;
	private Vector3 coreEndSize;
	private float lerpTime = 0.8f;
	private float currentLerpTime;

	private bool destroyCore = false;

	private int i = 0;


	// Use this for initialization
	void Start () {
		coreStartSize = Vector3.one * 0.01f;
		core.transform.localScale = coreStartSize;
		coreEndSize = Vector3.one;
//		SpawnProgram(i);			
	}
	
	// Update is called once per frame
	void Update () {

		if (Dictionaries.dictionaries.startGame && !Dictionaries.dictionaries.gameOver)
		{
			if (Time.time - lastSpawnTime >= nextSpawnTime)
			{
				SpawnProgram(i);
			}
		}
		if (!Dictionaries.dictionaries.startGame)
		{
			if (Input.anyKeyDown)
			{
				spawnCore = true;
			}
		}

		if (spawnCore)
		{
			core.SetActive(true);

			currentLerpTime += Time.deltaTime;

			
			float t = currentLerpTime / lerpTime;
			t = t*t*t * (t * (6f*t - 15f) + 10f);
			Vector3 vect = Vector3.Lerp(coreStartSize, coreEndSize, t);
			core.transform.localScale = vect;
			
			if (t >= 1f)
			{
				spawnCore = false;
			}
		}

		if (destroyCore)
		{
			currentLerpTime += Time.deltaTime;
						
			float t = currentLerpTime / lerpTime;
			t = t*t*t * (t * (6f*t - 15f) + 10f);
			Vector3 vect = Vector3.Lerp(coreStartSize, coreEndSize, t);
			core.transform.localScale = vect;
			
			if (t >= 1f)
			{
//				destroyCore = false;
				Destroy(core);
			}
		}

		if (Dictionaries.dictionaries.gameOver && !destroyCore)
		{
			coreStartSize = core.transform.localScale;
			coreEndSize = coreStartSize * 100f;
			currentLerpTime = 0f;
			destroyCore = true;
		}
	
	}

	public void SpawnProgram (int i)
	{
		i++;
		GameObject program = Instantiate(Resources.Load("Prefabs/program", typeof(GameObject)), transform.position + new Vector3 (0,Random.Range(-3.0f, 3.0f),0), Quaternion.identity) as GameObject;
		Vector2 dir = (destination.transform.position + new Vector3 (0, Random.Range(-1.0f, 1.0f), 0)) - program.transform.position;
		dir.Normalize ();
		dir *= Random.Range(minProgramSpeed, maxProgramSpeed);
		program.GetComponent<Rigidbody2D>().velocity = dir;
		float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
		program.transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
		lastSpawnTime = Time.time;
		nextSpawnTime = Random.Range(minSpawnTime, maxSpawnTime);
		program.name = "program" + i.ToString();
        program.GetComponent<SpriteRenderer>().sprite = Resources.Load<Sprite>("Programs/programs_" + Random.Range(0, 16));
    }
}
