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

public class WaveManager : MonoBehaviour {

	public static WaveManager instance;
	public GameObject WavePrefab;
	public int ScorePoints = 0;
	public UnityEngine.UI.Text Score;
	private float startInterval;
	public float Interval = 5F;
	private float lastSpawn;
	public float SpawnDistance = 30F;

	// Use this for initialization
	void Awake () {
		startInterval = Interval;
		if(WaveManager.instance == null) {
			WaveManager.instance = this;
		}
	}

	public void AddScore(int additionalScore) {
		ScorePoints += additionalScore;
		Score.text = ScorePoints.ToString();
	}
	
	// Update is called once per frame
	void Update () {
		if(Time.time >= lastSpawn+Interval) {
			SpawnWave();
		}
	}

	public void Reset() {
		IncomingWave[] waves = FindObjectsOfType<IncomingWave>();
		foreach(IncomingWave w in waves) {
			Destroy(w.gameObject);
		}
		Interval = startInterval;
		lastSpawn = 0;
		ScorePoints = 0;
		Score.text = "0";
		gameObject.SetActive(false);
	}

	void SpawnWave() {
		lastSpawn = Time.time;
		Vector3 spawnPos = getSpawnPos();
		Vector3 center = Camera.main.transform.position;
		center.y = 0;
		Quaternion spawnRot = Quaternion.LookRotation(center-spawnPos);
		GameObject wave = Instantiate(WavePrefab,spawnPos,spawnRot) as GameObject;
		PlayerShipController.instance.SetWaveDir(PlayerShipController.instance.NavigatorID,new Vector2(wave.transform.forward.x,wave.transform.forward.z));
	}

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