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

public class LeakHandler : MonoBehaviour {
	public GameScript gs;

	public List<Leak> leaks;
	List<Leak> activeLeaks;
	int MaxLeaks = 2, totalLeaks;
	float waterLevel = -100; 
	public Image Water;
	AudioSource NewLeakSound;
	public int leakCount;
	// Use this for initialization
	
	void Start () {
		activeLeaks = new List<Leak>();
		NewLeakSound = transform.Find("NewLeak").GetComponent<AudioSource>();
	}

	public void AddLeak(Leak lk) {
		leaks.Add(lk);
		activeLeaks.Remove(lk);
	}

	public void NewLeak() {
		//If there is room for more leaks
		if (activeLeaks.Count < MaxLeaks) {
			NewLeakSound.Play();
			//Choose one from the list
			Leak newLeak = leaks[Random.Range(0,leaks.Count)];
			//Add it to the active leaks and remove it from the whole list
			activeLeaks.Add(newLeak); 
			leaks.Remove(newLeak); 
			//Activate it
			newLeak.gameObject.SetActive(true);
			newLeak.Init();	
		} //Otherwise there is no room for more leaks, don't do anything.
	}

	public void firstLeak() {
		Invoke("StartLeaks",3);
	}

	public void StartLeaks() {
		if (totalLeaks < MaxLeaks) {
			totalLeaks++;
			NewLeak();
			Invoke("StartLeaks",Random.Range(5,20));
		}
	}

	/*public void NewLeak() {
		Leak newLeak = leaks[Random.Range(0,leaks.Count)];
		if (activeLeaks.Count >= MaxLeaks) {
			//We have maximum leaks.

			//leaks.Add(activeLeaks[0]);
			//activeLeaks[0].Leaking = false;
			//activeLeaks[0].gameObject.SetActive(false);
			//activeLeaks.Remove(activeLeaks[0]); 
		} else { //Make Up to MaxLeaks here first.
			Invoke("NewLeak",Random.Range(3,10));
		}
		//Add new leak
		//NewLeakSound.Play();
		activeLeaks.Add(newLeak); 
		newLeak.gameObject.SetActive(true);
		newLeak.Init();	
		leaks.Remove(newLeak); 
	} */

	public void Flood() {
		
		//Animation
		if (waterLevel < -15) {
			Water.rectTransform.localPosition = new Vector2(0, waterLevel*6);
			waterLevel+=2; //Flood Speed. BALANCE.
		} else {
			gs.GameOver();
		}
	}

	public void DrainWater() {
		if (waterLevel > -95) {
			waterLevel--; //Drain water while plugging holes. BALANCE.
			Water.rectTransform.localPosition = new Vector2(0, waterLevel*6);
		} 
	}

}
