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


public class PowerUpManager : MonoBehaviour {


    public GameObject powerUpPrefab;

    public Transform powerUpHolder;

    public float minPowerUpSpawnTime;
    public float maxPowerUpSpawnTime;

    public List<PowerUp> powerUpList = new List<PowerUp>();
    public List<SpawnPointProperties> powerUpSpawnList = new List<SpawnPointProperties>();

    void Start()
    {
        for(int i = 0; i < powerUpHolder.childCount; i++)
        {
            powerUpSpawnList.Add(powerUpHolder.GetChild(i).GetComponent<SpawnPointProperties>());
        }

        foreach(SpawnPointProperties spawn in powerUpSpawnList)
        {
            spawn.isUsable = true;
        }
    }

    void Update()
    {
        if(Input.GetKeyDown(KeyCode.Alpha1))
        {
            SpawnPowerUp();
        }
    }

    public void SpawnPowerUp()
    {
        int countUsable = 0;

        foreach (SpawnPointProperties spawn in powerUpSpawnList)
        {
            if (spawn.isUsable)
            {
                countUsable++;
            }
        }

        //Debug.Log("slot(s) left " + countUsable);

        if (countUsable == 0)
        {
            Debug.Log("No slot left");
            return;
        }

        int randomID = Random.Range(0, countUsable);

        int i = 0;

        foreach (SpawnPointProperties spawnPointProperties in powerUpSpawnList)
        {
            if (spawnPointProperties.isUsable && i++ == randomID)
            {             
                //Debug.Log("spawningPowerup at " + spawnPointProperties.name);
                GameObject powerUpInstance = Instantiate(powerUpPrefab, spawnPointProperties.transform.position, Quaternion.identity) as GameObject;
                powerUpInstance.transform.parent = spawnPointProperties.transform;
                powerUpInstance.name = "POWERUP_" + powerUpInstance.GetComponent<PowerUp>().m_powerUpType.ToString();
                spawnPointProperties.isUsable = false;
            }
        }
    }

    public void StartPowerUpLoop()
    {
        StartCoroutine("PowerUpLoop");
    }

    public IEnumerator PowerUpLoop()
    {
        while (gameObject.GetComponent<GameManager>().m_gameIsStarted)
        {
            SpawnPowerUp();
            //Debug.Log("spawning PowerUp");
            yield return new WaitForSeconds(Random.Range(minPowerUpSpawnTime, maxPowerUpSpawnTime));
        }
    }
}
