using UnityEngine;
using System.Collections.Generic;

public class Wave : MonoBehaviour
{
	public Wave right, left;
	
	public Vector2 direction;
	
	public float life;
	
	public static event System.EventHandler<WaveEventArgs> waveFired;
	
	public bool doesHit = true;
	
	void Update()
	{
		LineRenderer render = gameObject.GetComponent<LineRenderer>();
		if(right == null)
		{
			List<Vector3> points = new List<Vector3>();
			Wave next = this;
			while(next != null)
			{
				points.Add(next.transform.position);
				next = next.left;
			}
			render.enabled = true;
			render.numPositions = points.Count;
			render.SetPositions(points.ToArray());
			render.startWidth = life/50;
			render.endWidth = life/50;
			render.startColor = new Color(1, 1, 1, life/50);
			render.endColor = new Color(1, 1, 1, life/50);
		}
		else
			render.enabled = false;
		
		gameObject.GetComponent<CircleCollider2D>().radius = life/100;
	}
	
	void FixedUpdate()
	{
		transform.Translate(new Vector3(direction.x, direction.y, 0f));
		life--;
		if(life < 0)
			GameObject.Destroy(gameObject);
	}
	
	public static void createWave(Vector2 position, Vector2 centerDirection, float angle, int points, float lifetime, bool hits=true, bool makesSound=true)
	{
		float deltaAng = angle / points;
		Wave previous = null;
		GameObject prefab = (GameObject)Resources.Load("wave", typeof(GameObject));
		for(int i=0; i<points; i++)
		{
			GameObject point = GameObject.Instantiate(prefab, (Vector3)position, Quaternion.identity);
			point.transform.position = position;
			Wave wave = point.GetComponent<Wave>();
			wave.right = previous;
			if(previous != null)
				previous.left = wave;
			wave.direction = (Quaternion.AngleAxis((-angle/2) + (i+0.5f)*deltaAng, Vector3.forward) * centerDirection).normalized * 0.1f;
			wave.life = lifetime;
			previous = wave;
			wave.doesHit = hits;
		}
		if(waveFired != null && makesSound)
			waveFired(null, new WaveEventArgs{pos=position, strength=lifetime});
	}
	
	public class WaveEventArgs : System.EventArgs
	{
		public Vector3 pos {get; set;}
		public float strength {get; set;}
	}
}