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

public class SummoningParticleController : MonoBehaviour {

	public ParticleSystem baseParticles;
	public ParticleSystem subParticlePrefab;
	public ParticleSystem ringParticlePrefab;
	public ParticleSystem burstParticlePrefab;

	public Color[] runeColors;
	Color finalColor;
	// After spawning SummoningParticleController, you need to set runeColors, otherwise it will display a default anim
	float deathTimer;

	public List<Transform> particleXforms;

	void Start () {
		deathTimer = -1;
		particleXforms = new List<Transform>();
		Vector3 spawnPos = transform.position + new Vector3(0,1,0);
		float angle = 0;
		float deltaAngle = 360f/runeColors.Length;

		Vector3 tempVect = Vector3.zero;

		foreach (Color c in runeColors)
		{
			ParticleSystem ps = Instantiate<ParticleSystem>(subParticlePrefab);
			ps.transform.position = spawnPos + Quaternion.Euler (0,angle,0) * Vector3.forward * 2f;
			ps.startColor = c;
			ps.transform.SetParent(transform);
			particleXforms.Add (ps.transform);
			angle += deltaAngle;
			tempVect.x += c.r;
			tempVect.y += c.g;
			tempVect.z += c.b;
		}

		//average the colors
		tempVect = tempVect * 1f/runeColors.Length;
		float max = 0f;
		finalColor.r = tempVect.x * tempVect.x;
		if (max < finalColor.r) max = finalColor.r;
		finalColor.g = tempVect.y * tempVect.y;
		if (max < finalColor.g) max = finalColor.g;
		finalColor.b = tempVect.z * tempVect.z;
		if (max < finalColor.b) max = finalColor.b;
		finalColor.a = 1;
		finalColor.r *= 1f/max;
		finalColor.g *= 1f/max;
		finalColor.b *= 1f/max;

		baseParticles.startColor = finalColor;
		GenieDeathParticleController.baseColor = finalColor;
	}
	
	// Update is called once per frame
	void Update () {
		transform.Rotate(new Vector3(0,200*Time.deltaTime,0));
		float mag = 0;
		foreach (Transform t in particleXforms)
		{
			t.localPosition = t.localPosition * (1f - (0.9f * Time.deltaTime));
			mag = t.localPosition.magnitude;
		}
		if ((mag < 0.3f) && (deathTimer < 0))
		{
			foreach (ParticleSystem ps in GetComponentsInChildren<ParticleSystem>())
				ps.enableEmission = false;
			ParticleSystem burst = Instantiate<ParticleSystem> (burstParticlePrefab);
			ParticleSystem ring = Instantiate<ParticleSystem> (ringParticlePrefab);
			burst.transform.position = ring.transform.position = transform.position;
			burst.startColor = ring.startColor =  finalColor;
			burst.transform.SetParent(transform); 
			ring .transform.SetParent(transform); 
			deathTimer = 6;
		}
		if (deathTimer > 0)
		{
			deathTimer -= Time.deltaTime;
			if (deathTimer <= 0)
				Destroy (gameObject);
		}
	}
}
