using UnityEngine;
using System.Collections;

public class Laser_S : MonoBehaviour {
	
	LightColour col;
	LineRenderer line;
	GameObject source;
	float lifetime = 0.1f;
	
	float max_travel_distance = 10000;
	Vector3 hitpoint;
	Vector3 dir;
	public void SetLifetime(float newtime){lifetime = newtime;}
	public void SetColour(LightColour col){
		this.col = col;
	}
	public void SetSource(GameObject source, bool snap){
		this.source = source;
		snaptosource = snap;
	}
	bool snaptosource = false;
	void Start () {
		line = gameObject.GetComponent(typeof(LineRenderer)) as LineRenderer;		
		
		Color rgbColour = col.GetColourAsRGB();
		line.SetColors(rgbColour, rgbColour);
		
		line.SetPosition(0, transform.position);
		Matrix4x4 targetMatrix = Matrix4x4.TRS(transform.position, transform.rotation, Vector3.one); 
		Vector3 dirtarget = targetMatrix.MultiplyPoint(new Vector3(0, 0, max_travel_distance));
		dir = dirtarget-transform.position;
		
		RaycastHit[] hits = Physics.RaycastAll (transform.position, dir, max_travel_distance);
		float closest = Mathf.Infinity;
		RaycastHit hit = new RaycastHit();
		foreach(RaycastHit cycleHit in hits){
			if(cycleHit.distance < closest && cycleHit.collider.gameObject != source){
				closest = cycleHit.distance;
				hit = cycleHit;
			}
		}
		if (closest < Mathf.Infinity) {
			line.SetPosition(1, hit.point);
			hitpoint = hit.point;
			hit.collider.gameObject.SendMessage("HitByLaser", this, SendMessageOptions.DontRequireReceiver);			
		}else{
			line.SetPosition(1, dirtarget);
		}
		
	}
	
	void Update () {
		
		lifetime -= Time.deltaTime;
		
		if(lifetime < 0){
			Destroy (gameObject);
		}
		if(snaptosource && source != null){
			line.SetPosition(0, source.transform.position);
		}
	}	

	public LightColour GetCol(){return col;}
	public Vector3 GetDir(){return dir;}
	public Vector3 GetHit(){return hitpoint;}
	
	
}
