using UnityEngine;
using System.Collections;

public class Laser : Weapon
{
	[SerializeField]LineRenderer laserRay = null;//set from editor
	[SerializeField]float rayWidth = 0.2f; //set from editor
	[SerializeField]float rayTime = 0.6f; //set from editor
	[SerializeField]AnimationCurve rayIntensity = new AnimationCurve(new Keyframe[] {
		new Keyframe(0.0f, 0),
		new Keyframe(0.5f, 1f),
		new Keyframe(1.0f, 0),
	});
	[SerializeField]GameObject startPoint = null; //set from editor

	float rayTimer = 0;

	public override void Fire() {
		if (reloadTimer <= 0) {
			reloadTimer = fullReloadTime;
			if (enemy != null)
			{
				Vector3 emmiterPosition = transform.position;
				if (startPoint != null)
				{
					emmiterPosition = startPoint.transform.position;
				}
				if (Random.Range(0, 1f) < hitChance) {
					Vector3 hitPosition = enemy.GetRandomHitPoint();
					ShowRay(emmiterPosition, hitPosition);
					enemy.OnHit (damage, hitPosition);
				}
				else
				{ // miss
					// TODO
					Vector3 missPoint = enemy.GetRandomMissPoint();
					TextEffect.Show(enemy.GetRandomHitPoint(), "miss", Color.white, Vector3.up);
					ShowRay(emmiterPosition, missPoint + (missPoint - transform.position) * 4f);
				}
			}
		}
	}

	public void ShowRay (Vector3 from, Vector3 to)
	{
		rayTimer = rayTime;
		if (laserRay != null)
		{
			laserRay.SetVertexCount (2);
			laserRay.SetPosition(0, from);
			laserRay.SetPosition(1, to);
		}
	}

	void Update () {
		UpdateReload ();
		if (rayTimer > 0)
		{
			rayTimer -= Time.deltaTime;
			if (laserRay != null)
			{
				float width = rayWidth * rayIntensity.Evaluate(1f - rayTimer / rayTime);
				laserRay.SetWidth(width, width);
			}
		}
	}
}
