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

public class GameManager : MonoBehaviour
{
	public int lives;

	[Space(10)]

	public GameObject player;
	public Vector3 ascendAmount;
	public float ascendDelay;
	public float ascendTime;
	public iTween.EaseType easeAscend;

	public AudioClip ascendSound;
	public AudioClip loseSound;
	public AudioClip winSound;

	public AudioMixer mixer;

	public static GameManager instance;

	private void Awake()
	{
		instance = this;

		Killzone.OnKill.AddListener(OnKill);
		Cordeiro.OnAnyCordeiroRemove.AddListener(OnAnyCordeiroRemove);

		iTween.CameraFadeAdd();
		iTween.CameraFadeFrom(1, 1);

		iTween.ValueTo(gameObject, iTween.Hash("from", -80, "to", 0, "onupdate", "SetVolume", "time", 0, "easetype", iTween.EaseType.easeInOutSine));
	}

	private void OnKill()
	{
		lives--;
		if(lives < 0) 
		{
			print("GAMEOVER!");
			StartCoroutine(RestartDelayed(8));

			if(loseSound != null) AudioSource.PlayClipAtPoint(loseSound, Camera.main.transform.position);
			iTween.ValueTo(gameObject, iTween.Hash("from", 0, "to", -80, "onupdate", "SetVolume", "time", 2));
		}
	}

	private IEnumerator RestartDelayed(float delay)
	{
		yield return new WaitForSeconds(delay*0.5f);
		iTween.CameraFadeTo(1, delay*0.5f);
		yield return new WaitForSeconds(delay*0.5f);
		SceneManager.LoadScene(SceneManager.GetActiveScene().name);
	}

	private void OnAnyCordeiroRemove()
	{
		if(Cordeiro.allCordeiros.Count == 0 && isActiveAndEnabled) StartCoroutine(AllCordeirosGot(4));
	}

	[ContextMenu("TestEnd")]
	private void TestEnd()
	{
		StartCoroutine(AllCordeirosGot(4));
	}

	private IEnumerator AllCordeirosGot(float delay)
	{
		if(winSound != null) AudioSource.PlayClipAtPoint(winSound, Camera.main.transform.position);

		if(ascendSound != null) AudioSource.PlayClipAtPoint(ascendSound, Camera.main.transform.position, 0.5f);
		player.GetComponentInChildren<Animator>().SetBool("Win", true);

		iTween.MoveAdd(player.gameObject, iTween.Hash("amount", ascendAmount, "time", ascendTime,
		"easetype", easeAscend, "delay", ascendDelay, "oncomplete", "AscendComplete"));

//		player.GetComponentInChildren<Collider2D>().enabled = false;
//		player.GetComponentInChildren<Rigidbody2D>().isKinematic = true;

		player.BroadcastMessage("ArcoBegin");

		iTween.ValueTo(gameObject, iTween.Hash("from", 0, "to", -80, "onupdate", "SetVolume", "time", 2));

		//

		yield return new WaitForSeconds(delay*0.5f);

		iTween.CameraFadeTo(1, delay*0.5f);

		yield return new WaitForSeconds(delay);

		print("All Cordeiros Got!!");
		SceneManager.LoadScene("Menu");
	}

	private void SetVolume(float value)
	{
		mixer.SetFloat("volume", value);
	}
}