using System.Collections.Generic;
using UnityEngine;

public class EnemiesSpawner : Simpleton<EnemiesSpawner> {

	public int Level = 0;

	private List<EnemySpawn> enemies;
	private List<Vector3> enemyPositions;
	private int spawnedEnemies;
	private int spawnedGhosts;

	private float timeOfLastSpawn;

	public void Start() {
		this.enemies = LevelManager.Instance.GetLevelEnemies(Level);
		enemyPositions = new List<Vector3>();
		this.timeOfLastSpawn = this.enemies[this.enemies.Count - 1].SpawnAfter;
		foreach (var enemy in enemies) {
			Invoke("SpawnEnemy", enemy.SpawnAfter);
			Invoke("SpawnGhost", Mathf.Max(0, enemy.SpawnAfter - 1.2f));
			enemyPositions.Add(Camera.main.ViewportToWorldPoint(new Vector3(Random.Range(.1f, .7f), 1.1f, 10)));
		}
	}

	public void Update() {
		 if (Time.timeSinceLevelLoad > this.timeOfLastSpawn + 1 && transform.childCount == 0) {
			 LevelManager.Instance.LevelComplete();
		 }
	}

	private void SpawnEnemy() {
		var enemySpawn = enemies[this.spawnedEnemies];

		var enemy = Instantiate(
			enemySpawn.Enemy,
			enemyPositions[this.spawnedEnemies], 
			transform.rotation, 
			transform);
		enemy.GetComponent<Rigidbody2D>().AddForce(new Vector2(Random.Range(-.3f, .3f), 0));
		enemy.transform.rotation = Quaternion.AngleAxis(Random.Range(-30, 30), Vector3.forward);

		if (enemySpawn.BattleCry != null) {
        	AudioSource.PlayClipAtPoint(enemySpawn.BattleCry, transform.position);
		}

		this.spawnedEnemies++;
	}

	private void SpawnGhost() {
		var position = new Vector2(enemyPositions[this.spawnedGhosts].x, .75f * enemyPositions[this.spawnedGhosts].y);
		this.spawnedGhosts++;

		if (this.spawnedGhosts > 1) {
			Instantiate(LevelManager.Instance.GhostPrefab, position, transform.rotation, transform);
		}

	}
}
