using UnityEngine;
using System.Collections;

public class SpawnMoreEnemiesComponent : MonoBehaviour
{
    private EnemyAI myAI;

    public GameObject Prefab_MensToSpawn;
    public Vector2 MinMax_NumToSpawn;
    public float TimeBetweenSpawns;

    void Awake()
    {
        myAI = GetComponent<EnemyAI>();
    }

	// Use this for initialization
	void Start () 
    {
        if (myAI != null)
            myAI.AddAltFireFunction(OnSpawnMyMens);
	}

    public bool OnSpawnMyMens(GameObject spawnObject)
    {
        PlayerController thePlayer = GameObject.Find("Player").GetComponent<PlayerController>();
        if ((thePlayer.transform.position - transform.position).sqrMagnitude > 50.0f * 50.0f)
            return false;

        StartCoroutine(SpawnMensCoroutine(transform.position));
        return true;
    }

    IEnumerator SpawnMensCoroutine(Vector3 vSpawnPosition)
    {


        int iNumToSpawn = Random.Range((int) MinMax_NumToSpawn.x, (int) MinMax_NumToSpawn.y + 1);
        for (int t = 0; t < iNumToSpawn; t++)
        {
            GameObject newMans = Instantiate(Prefab_MensToSpawn);
            newMans.transform.position = vSpawnPosition;
            AIMove_Base moveComponent = newMans.GetComponent<AIMove_Base>();
            if (moveComponent != null)
            {
                Vector2 vKickDir = Random.insideUnitCircle;
                vKickDir.Normalize();
                moveComponent.AddImpulse( vKickDir  * 30.0f );
            }
            yield return new WaitForSeconds(TimeBetweenSpawns);
        }
    }

}
