using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using DG.Tweening;

public class GameManager : MonoBehaviour
{
	public int score;
	public float timeLeft;

	public Text scoreText;
	public Text timeText;

	public GameObject magnet;

	public GameObject gameOverUI;
	public Text gameOverScoreText;
	public GameObject scoreUI;
	public GameObject timeUI;

	[SerializeField]
	private bool paused;

	private void Start()
	{
		ResetGame();
	}

	private void Update()
	{
		if(Input.GetKeyDown(KeyCode.Escape))
		{
			SceneManager.LoadScene(0);
		}

		if(paused)
		{
			return;
		}

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

			if(timeLeft < 0f)
			{
				timeLeft = 0f;

				EndGame();
			}

			timeText.text = ((int)timeLeft).ToString();
		}
	}

	public void AddScore(int points)
	{
		score += points;

		scoreText.text = score.ToString();
	}

	public void ResetGame()
	{
		score = 0;
		timeLeft = 60f;

		ResumeGame();
		AddScore(0);
	}

	public bool IsPaused()
	{
		if(timeLeft <= 0f)
		{
			return true;
		}

		return paused;
	}

	public void PauseGame()
	{
		paused = true;
	}

	public void ResumeGame()
	{
		paused = false;
	}

	public void EndGame()
	{
		magnet.transform.DOMove(new Vector3(-17.12f, 33.3f, 22.48f), 0.2f);

		Invoke("CompleteStuff", 0.2f);

		gameOverScoreText.text = score.ToString();
		gameOverUI.SetActive(true);
		scoreUI.SetActive(false);
		timeUI.SetActive(false);
	}

	void CompleteStuff() {
		var targets = Physics.OverlapSphere (magnet.transform.position, 50f);

		foreach (var target in targets) 
		{
			if(target.gameObject == magnet || target.gameObject.tag == "Player")
			{ continue; }

			Rigidbody rb = target.GetComponent<Rigidbody> ();

			rb.DOMove(magnet.transform.position - Vector3.up * 4f, 1f).OnComplete(() =>
			{
				rb.isKinematic = true;
			});
		}
	}
}
