using UnityEngine;
using System.Collections;

public class PowerUpController : MonoBehaviour 
{
    private MegaShoot _Player1Special = null;
    private MegaShoot _Player2Special = null;

    private GameObject[] _PowerUpSpawners;
    private GameObject _PowerUpInstance = null;
    private float _TimeToWait = float.MaxValue;

    public float MinTimeInterval = 10f;
    public float MaxTimeInterval = 40f;

    public GameObject PowerUp = null;

	void Start () 
    {
        _PowerUpSpawners = GameObject.FindGameObjectsWithTag("PowerUpSpawn");

        GameObject player1 = GameObject.Find("Player1");

        if (player1 != null)
        {
            _Player1Special = (MegaShoot) player1.GetComponent(typeof(MegaShoot));
        }

        GameObject player2 = GameObject.Find("Player2");

        if (player2 != null)
        {
            _Player2Special = (MegaShoot) player2.GetComponent(typeof(MegaShoot));
        }

        _TimeToWait = Mathf.Lerp(MinTimeInterval, MaxTimeInterval, Random.Range(0f, 1f));

        Debug.Log("[" + gameObject.name + "] Next PowerUp in : " + _TimeToWait + " seconds.");
	}
	
	void Update () 
    {
        if (_Player1Special != null)
        {
            if (_Player1Special.bCanShoot)
            {
                return;
            }
        }

        if (_Player2Special != null)
        {
            if (_Player2Special.bCanShoot)
            {
                return;
            }
        }

        if (_PowerUpSpawners.Length == 0)
        {
            return;
        }

        if (_PowerUpInstance == null)
        {
            _TimeToWait -= Time.deltaTime;

            if (_TimeToWait < 0f)
            {
                // Select a random spawn point.

                int index = Random.Range(0, _PowerUpSpawners.Length - 1);

                GameObject spawnPoint = _PowerUpSpawners[index];

                if (spawnPoint != null)
                {
                    if (!GameManager.Instance.GameOver)
                    {
                        _PowerUpInstance = (GameObject)Instantiate(PowerUp, spawnPoint.transform.position, spawnPoint.transform.rotation);
                    }
                }

                _TimeToWait = Mathf.Lerp(MinTimeInterval, MaxTimeInterval, Random.Range(0f, 1f));

                Debug.Log("[" + gameObject.name + "] Next PowerUp in : " + _TimeToWait + " seconds.");
            }
        }
	}
}
