using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class Shooting : MonoBehaviour {

	public float range = 100f ;
	public float ammo = 100 ;
    public float ammoLossSpeed = 10.0f;
	public Slider ammoSlider ;

	bool triggerDown ;
	bool fireHit ;
	Ray shootRay;
	RaycastHit shootHit;
	ParticleSystem particles;
	int shootableMask;


	// Use this for initialization
	void Awake () 
	{
		shootableMask = LayerMask.GetMask ("Shootable");
		particles = GetComponent<ParticleSystem> ();
		triggerDown = false ;
		fireHit = false ;
	}
	
	// Update is called once per frame
	void Update () 
	{
		if(Input.GetButtonDown("Fire1") && ammo > 0)
		{
			triggerDown = true ;
            particles.loop = true;
            particles.Play();
			this.collider.enabled = true;
			Shoot() ;
		}
	    else if (Input.GetButtonUp("Fire1"))
	    {
            particles.loop = false;
            particles.Stop();
			this.collider.enabled = false;
		}
        else if(Input.GetButton("Fire1"))
        {
            ammo -= ammoLossSpeed * Time.deltaTime;
            ammoSlider.value = ammo;

            if(ammo < 0)
            {
                ammo = 0;
            }
        }
		else
		{
			triggerDown = false ;
			fireHit = false ;
		}
	}

	void Shoot ()
	{
		shootRay.origin = transform.position;
		shootRay.direction = transform.forward;

		if(Physics.Raycast (shootRay, out shootHit, range, shootableMask))
		{
			fireHit = true ;
		}
		else
			fireHit = false ;
	}
}
