using UnityEngine;
using System.Collections;

public class LevelSpawner : MonoBehaviour
{
    public GameObject[] LevelBasePrefabs;

    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }

    public void InitLevel()
    {
        ClearLevel();

        var gamePlayManager = GameManager.instance.GamePlayManager;

        // Spawn levelBase

        int levelBaseIndex = Random.Range(0, LevelBasePrefabs.Length);

        var levelBase = Instantiate(LevelBasePrefabs[levelBaseIndex]).GetComponent<LevelBase>();
        levelBase.transform.SetParent(transform, false);

        // Spawn Player Objects

        for(int player = 0; player < 2; player++)
        {
            var playerController = gamePlayManager.Players[player];

            int summonAreaIndex = Random.Range(0, levelBase.SummonAreaPrefabs.Length);
            var summonArea = Instantiate(levelBase.SummonAreaPrefabs[summonAreaIndex]).GetComponent<SummonArea>();
            summonArea.transform.SetParent(levelBase.PlayerSummonAreaPositions[player], false);
            
            int playerTowerIndex = Random.Range(0, levelBase.PlayerTowerPrefabs.Length);
            var playerTower = Instantiate(levelBase.PlayerTowerPrefabs[playerTowerIndex]).GetComponent<Tower>();
            playerTower.transform.SetParent(levelBase.PlayerTowerPositions[player], false);

            playerController.SetPlayerObjects(summonArea, playerTower);
        }

        // Spawn Time Object

        int timerIndex = Random.Range(0, levelBase.TimerPrefabs.Length);
        var timer = Instantiate(levelBase.TimerPrefabs[timerIndex]).GetComponent<CountdownTimer>();
        timer.transform.SetParent(levelBase.TimerPosition, false);

        gamePlayManager.SetTimerObject(timer);
    }

    public void ClearLevel()
    {
        //Clear existing level.

        foreach (Transform child in transform)
        {
            Destroy(child.gameObject);
        }
    }
}
