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

public class PickupController : MonoBehaviour {

	public int numPickups = 3;
	private GameObject[] spawnPointList;
	private GameObject[] pickupObjects;
	private int numSpawnPoints;
	private int numPickupTypes;
	private bool[] availableSpawnPoints;
    private int numAvailableSpawnPoints;
    // Use this for initialization
    void Start () 
	{
		
	}

	void Awake()
	{
		spawnPointList = GameObject.FindGameObjectsWithTag("SpawnPoint");
		pickupObjects = GameObject.FindGameObjectsWithTag("Pickups");
		numSpawnPoints = spawnPointList.Length;
        
        numPickupTypes = pickupObjects.Length;

        numAvailableSpawnPoints = numPickups;

        availableSpawnPoints = new bool[numSpawnPoints];

		if(numPickups>numSpawnPoints)
		{
			numPickups = numSpawnPoints;
		}
		for(int i=0;i<numSpawnPoints;++i)
		{
			availableSpawnPoints[i] = true;
		}
		for(int i=0;i<numPickups;++i)
		{
			SpawnPickup();
		}
	}

    // Update is called once per frame
    void Update()
    {
        Debug.Log("numAvailableSpawnPoints "+numAvailableSpawnPoints);
        Debug.Log("numPickups " + numPickups);
        if (numAvailableSpawnPoints> 0)
        {
            SpawnPickup();
        }
    
            Debug.Log("for");
    
    }

    void SpawnPickup()
	{
		int randomSpawnIndex = Random.Range(0, numSpawnPoints);
		int randomPickup = Random.Range(0, numPickupTypes);
        int randomSpecialPickup = Random.Range(0, 1000);

        while (randomPickup == 1 && randomSpecialPickup <= 700 )
        {
            randomPickup = Random.Range(0, numPickupTypes);
        }

        while (!availableSpawnPoints[randomSpawnIndex])
		{
			randomSpawnIndex = Random.Range(0, numSpawnPoints);
        }

        Vector3 spawnPickupPos = spawnPointList[randomSpawnIndex].transform.position;
		GameObject pickup = Instantiate(pickupObjects[randomPickup])as GameObject;
		pickup.transform.position = spawnPickupPos;
        pickup.name = randomSpawnIndex.ToString();
       /* PickUp pickupScript = pickup.GetComponent<PickUp>();
        if(pickupScript)
        {*/
            pickup.GetComponent<PickUp>().index = randomSpawnIndex;
            pickup.GetComponent<PickUp>().canMove = true;
        //}        
		availableSpawnPoints[randomSpawnIndex] = false;
        numAvailableSpawnPoints--;
        if(numAvailableSpawnPoints<0)
        {
            numAvailableSpawnPoints = 0;
        }
    }

    public void ResetSpawnPoint(int spawnIndex)
    {
        availableSpawnPoints[spawnIndex] = true;
        numAvailableSpawnPoints++;
        if (numAvailableSpawnPoints > numPickups)
        {
            numAvailableSpawnPoints = numPickups;
        }
    }
}
