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

public class GunController : MonoBehaviour {

	public bool isFiring = false;
	public GameObject missile;
	public int pooledAmount = 15;

	public float missileSpeed;
	public float missileTime;
	public float Accuracy;
	public float CD = 0.5f;

	public AudioClip shotSound;
	public float minSoundRange;
	public float maxSoundRange;

	List<GameObject> missiles;

	private float shotCounter;
	
	public Transform firePoint;

	public GameManager playerManager;


	void Start () {
		
		playerManager = FindObjectOfType <GameManager>();

		missiles = new List<GameObject>();
		for (int i = 0; i < pooledAmount; i++){
			GameObject obj = (GameObject)Instantiate(missile);
			obj.SetActive(false);
			missiles.Add(obj);
		}

	}
	

	void Update () {

		if (playerManager.gamePaused == false & playerManager.playerFreezed == false & playerManager.playerAntiFire == false){


		if(shotCounter > 0){
		shotCounter -= Time.deltaTime;}

		if (isFiring)
		{

			if (shotCounter <= 0)
			{


			for (int i=0; i<missiles.Count; i++)
			{
				if (!missiles[i].activeInHierarchy)
				{
					missiles[i].transform.position = firePoint.position;
					missiles[i].transform.rotation = firePoint.rotation;
					missiles[i].SetActive(true);

			shotCounter = CD;

			GetComponent<AudioSource>().pitch = Random.Range(minSoundRange, maxSoundRange);
			GetComponent<AudioSource>().PlayOneShot(shotSound);
			
			missiles[i].transform.Rotate((Vector3.forward + new Vector3 (0, Random.Range(-Accuracy, Accuracy), 0)) * 1);
			missiles[i].GetComponent<GunMissile>().speed = missileSpeed;
			missiles[i].GetComponent<GunMissile>().lifetime = missileTime;

					break;

				}}}
		}
		}
		else {isFiring = false;}
		}
}
			