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

public class Gameplay : MonoBehaviour {

	public float timeMultipler = 0.0f;

	private bool pausing;

	private float deathTime = 0;

	public AudioSource pirateMusic;
	public AudioSource scientistMusic;
	public Sprite pirateSprite;
	public Sprite scientistSprite;

	public PlayerShip playerShip;
	public PlayerSelect playerSelect;

	public StoryManager storyManager;

	public DangerManager dangerManager;

	public MessageDisplay messageDisplay;

	// Use this for initialization
	void Start () {
		timeMultipler = 0.0f;
		deathTime = 0;
	}

	public void StartGame(string charName)
	{
		playerShip.gameObject.SetActive(true);
		playerShip.Restart();

		dangerManager.Restart();
		storyManager.Restart(charName);

		if (charName == "pirate")
		{
			playerShip.GetComponent<SpriteRenderer>().sprite = pirateSprite;
			pirateMusic.Play();
		}
		else if (charName == "scientist")
		{
			playerShip.GetComponent<SpriteRenderer>().sprite = scientistSprite;
			scientistMusic.Play();
		}

		messageDisplay.SetDisplayChar(charName);

		timeMultipler = 1.0f;
		deathTime = 0;
	}

	public void EndGame()
	{
		pirateMusic.Stop();
		scientistMusic.Stop();

		playerShip.gameObject.SetActive(false);
		deathTime = 1.0f;
	}

	public void DisplayMessage(string message, int expression)
	{
		timeMultipler = 0;
		messageDisplay.ShowMessage(message, expression);
	}
	
	// Update is called once per frame
	void Update () {

		pirateMusic.volume = timeMultipler * 0.9f + 0.1f;
		scientistMusic.volume = timeMultipler * 0.9f + 0.1f;

		if (Input.GetKeyDown(KeyCode.P))
			togglePause();

		if (pausing)
			{
				if (timeMultipler > 0)
					timeMultipler += 0.5f * Time.deltaTime;
				if (timeMultipler >= 1.0f)
				{
					pausing = false;
					timeMultipler = 1.0f;
				}
			}

		if (deathTime > 0)
			{
				deathTime -= Time.deltaTime;

				if (deathTime <= 0)
				{
					playerSelect.gameObject.SetActive(true);

					Start();
					deathTime = 0;
				}
			}
	
	}

	public void togglePause() {
		if (pausing)
			return;

		if (timeMultipler == 1.0f)
		{
			timeMultipler = 0;
		}
		else
		{
			timeMultipler = 0.5f * Time.deltaTime;
			pausing = true;
		}
	}
}
