using UnityEngine;
using System.Collections;

public class Plasma : Weapon
{
	[SerializeField]int shotCount = 10; // bullets in a line
	[SerializeField]float shotDelay = 0.08f; // delay in seconds between shots
	[SerializeField]float bulletSpeed = 20f; // unit per second Set from editor
	[SerializeField]GameObject bulletReference = null; // bullet
	[SerializeField]GameObject[] startPoints = null; // gun fire point
	int startPointId = 0;

	GameObject[] bulletPool = null;

	public override void Fire() {
		if (reloadTimer <= 0) {
			reloadTimer = fullReloadTime;
			if (enemy != null)
			{
				if (bulletPool != null)
				{
					for(int i = 0; i < bulletPool.Length; i++)
					{
						int num = i;
						Vector3 startPoint = transform.position;
						if (startPoints != null && startPoints.Length > 0)
						{
							startPointId ++;
							startPointId = startPointId % startPoints.Length;
							if (startPoints[startPointId] != null)
							{
								startPoint = startPoints[startPointId].transform.position;
							}
						}
						Vector3 endPoint = enemy.GetRandomHitPoint();
						float distance = (endPoint - startPoint).magnitude;
						bulletPool[num].SetActive(true);
						Timer.Add((float)i * -shotDelay, distance / bulletSpeed, (anim) => {
							bulletPool[num].transform.position = Vector3.Lerp(startPoint, endPoint, anim);
						},
						() => {
							bulletPool[num].transform.localPosition = Vector3.zero;
							bulletPool[num].SetActive(false);
							enemy.OnHit (damage, endPoint);
						});
					}
				}
			}
		}
	}

	void Start()
	{
		GenerateBulletPool ();
	}

	void GenerateBulletPool()
	{
		if (bulletReference != null)
		{
			bulletPool = new GameObject[shotCount];
			for (int i = 0; i < bulletPool.Length; i++)
			{
				bulletPool[i] = Instantiate(bulletReference);
				bulletPool[i].transform.parent = transform;
				bulletPool[i].transform.localPosition = Vector3.zero;
			}
		}

	}

	void Update () {
		UpdateReload ();
	}
}
