using UnityEngine;
using System.Collections;

public class EnemySpawner : MonoBehaviour {

    public GameObject enemy;

    public float spawnRadius = 5.0f;

    public float cooldownTime = 30f;

    public int spawnCount = 3;

    enum SpawnerState { ready, cooldown };
    private SpawnerState spawnerState = SpawnerState.ready;

    public bool isStronk = false;

	// Use this for initialization
	void Start () {
        EventManager.OnStronkStart += StronkStart;
	}
	
	// Update is called once per frame
	void Update () {
	
	}

    IEnumerator Spawn()
    {
        StartCoroutine(Cooldown());
        for(int i = 0; i < spawnCount; i++)
        {
            SpawnEnemy();
            yield return new WaitForSeconds(Random.Range(0.1f, 0.4f));
        }
    }

    void SpawnEnemy()
    {
        Vector3 pos = new Vector3(Random.Range(-spawnRadius, spawnRadius), Random.Range(-spawnRadius, spawnRadius), Random.Range(-spawnRadius, spawnRadius));
        pos = transform.position + pos;
        NavMeshHit hit;
        if (NavMesh.SamplePosition(pos, out hit, spawnRadius/2, NavMesh.AllAreas))
        {
            pos = hit.position;
        }
        GameObject newEnemy = (GameObject)Instantiate(enemy, pos, Quaternion.identity);
        string type = "";
        if (isStronk) { type = "stronk"; }
        newEnemy.GetComponent<Enemy>().OnSpawn(type);

        Debug.Log("Spawned!");
    }

    IEnumerator Cooldown()
    {
        spawnerState = SpawnerState.cooldown;
        yield return new WaitForSeconds(cooldownTime);
        spawnerState = SpawnerState.ready;
    }

    void OnTriggerEnter(Collider other)
    {
        if (spawnerState == SpawnerState.ready && other.CompareTag("Player"))
        {
            StartCoroutine(Spawn());
        }
    }

    void StronkStart(float time)
    {
        StartCoroutine(StronkTimer(time));
    }

    IEnumerator StronkTimer(float time)
    {
        isStronk = true;
        yield return new WaitForSeconds(time);
        isStronk = false;
    }
}
