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

public class EnemyManager : MonoBehaviour {

	public static EnemyManager instance;
	public GameObject EnemyPrefab;

	private float startInterval;
	public float SpawnIntervall = 20F;
	private float lastSpawn = 0;

	public float SpawnDistance = 10F;

	public int MaxShips = 2;
	

	// Use this for initialization
	void Awake () {
		if(EnemyManager.instance == null) {
			EnemyManager.instance = this;
		}
		startInterval = SpawnIntervall;
	}
	
	// Update is called once per frame
	void Update () {
		if(Time.time >= lastSpawn + SpawnIntervall) {
			SpawnEnemy();
		}
	}

	
	void SpawnEnemy() {
		if(GameObject.FindObjectsOfType<EnemyShipController>().Length >= MaxShips) { return; }
		Vector3 spos = getSpawnPos();
		
		  
		lastSpawn = Time.time;
		GameObject en = Instantiate(EnemyPrefab,spos,Quaternion.identity) as GameObject;
		en.GetComponent<EnemyShipController>().SetPlayerPos();
	}

	public void Reset() {
		EnemyShipController[] en = FindObjectsOfType<EnemyShipController>();
		foreach(EnemyShipController e in en) {
			Destroy(e.gameObject);
		}
		SpawnIntervall = startInterval;
		lastSpawn = 0;
		gameObject.SetActive(false);
	}


	Vector3 getSpawnPos() {
		Vector3 center = Camera.main.transform.position;
		center.y = 0;
		center += PlayerShipController.instance.transform.right*Random.Range(-18F,18F);
		center += PlayerShipController.instance.transform.forward*-SpawnDistance;
		return center;
	}
}
