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

public class TeleporterScript : MonoBehaviour {

	public string NextLevelName;
	public AudioClip winSong;
	public Sprite openSprite;
	public Sprite closedSprite;
	private GlobalEnums.ActivityState currentActivityState;

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		if(GameObject.FindGameObjectWithTag ("Player").GetComponent<PlayerScript> ().BatteryCount () >= MaxBatteries()) {
			currentActivityState = GlobalEnums.ActivityState.Open;
			this.GetComponent<SpriteRenderer> ().sprite = openSprite;
		}
		else
		{
			this.GetComponent<SpriteRenderer> ().sprite = closedSprite;
			currentActivityState = GlobalEnums.ActivityState.Closed;
		}
	}

	protected void OnTriggerEnter2D(Collider2D col) 
	{
		if(col.gameObject.tag == "Player" && currentActivityState == GlobalEnums.ActivityState.Open) {
			StartCoroutine (Won());

		}
	}

	public int MaxBatteries()
	{
		GameObject[] batteries = GameObject.FindGameObjectsWithTag ("Battery");
		return batteries.Length;
	}

	IEnumerator Won()
	{
		GameObject.FindGameObjectWithTag ("Canvas").GetComponent<UIManagerScript> ().PauseGame ();
		GameObject.FindGameObjectWithTag ("Player").GetComponent<PlayerScript> ().StopAllMusic ();
		float lengthLeft = winSong.length;
		this.GetComponent<AudioSource> ().clip = winSong;
		this.GetComponent<AudioSource> ().loop = false;
		this.GetComponent<AudioSource> ().Play ();

		while (lengthLeft > 0)
		{
			lengthLeft -= Time.fixedDeltaTime;

			yield return new WaitForFixedUpdate();
		}

		yield return new WaitForSeconds (1f);

		SceneManager.LoadScene (NextLevelName);
	}


}

