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

public class PlayerFire : MonoBehaviour {

	public float CamRayLength = 100f;
	public Vector3 StartP;
	//Projectiles for spawn
	public GameObject MainGunProj;

	private int HitMask;
	private Vector3 EndP;
	private Vector3 HoldStart;
	private Vector3 HoldEnd;
	private int MainGunPhase = 0;

	void Awake(){
		HitMask = LayerMask.GetMask ("Shootable");
		HoldStart = StartP;
		HoldEnd = EndP;
	}

	void FireMainGun(float InFired){
		if (InFired == 1) {
			//print ("fireGun");
			Ray CamRay = Camera.main.ScreenPointToRay (Input.mousePosition);
			RaycastHit RayTarget;

			if (Physics.Raycast (CamRay, out RayTarget, CamRayLength, HitMask)) {
				//print (RayTarget.transform.gameObject);

				//Draw the ray to show where it will hit;
				this.GetComponent<LineRenderer> ().enabled = true;
				EndP =  RayTarget.point - this.transform.position;
				HoldEnd = RayTarget.point - this.transform.position;
				//EndP = Quaternion.AngleAxis(-30, Vector3.up) * EndP;

				EndP = Quaternion.Inverse(this.transform.rotation) * EndP;
				//StartP = Quaternion.Inverse(this.transform.rotation) * HoldStart;
				this.transform.rotation = Quaternion.Lerp(this.transform.rotation,Quaternion.LookRotation(HoldEnd), 10*Time.deltaTime);

				this.GetComponent<LineRenderer> ().SetPosition (0, HoldStart);
				this.GetComponent<LineRenderer> ().SetPosition (1, EndP);
				MainGunPhase = 1;
			}
		} else {
			//If the player isn't aming don't draw the path
			this.GetComponent<LineRenderer> ().enabled = false;
			if (MainGunPhase == 1) {
				MainGunPhase = 0;
				//StartP = Quaternion.Inverse(this.transform.rotation) * HoldStart;
				Instantiate (MainGunProj,this.transform.GetChild(0).position, this.transform.rotation);
			}
		}
	}
	
	// Update
	void FixedUpdate () {
		//print ("FireFixedUpdate");
		float Firing = Input.GetAxis ("Fire1");
		FireMainGun (Firing);
	}
}
