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

public class StateHandlerS : MonoBehaviour {

	public const int MAX_LEVEL = 5;
	public int levelNumber;

	public const int DURING_LEVEL = 0;
	public const int AFTER_LEVEL = 1;
	public int currentState;

	public int levelTime;

	public int scoreCount;
	public int crushCount;
	public int requiredScore;

	private float exactTime;
	private int time;
	private bool failed;

	public Text scoreCountText;
	public Text timeText;
	public RectTransform midPanel;
	public Text panelCaption;
	public Text panelInnerText;

	public CatcherS catcher;
	public BallS ball;

	void Start() {
		exactTime = levelTime;
	}

	void Update () {
		int remainingMinutes = time / 60;
		int remainingSeconds = time % 60;
		scoreCountText.text = " Collected: " + scoreCount;
		timeText.text = twoDigited(remainingMinutes) + " : " + twoDigited(remainingSeconds);

		if (exactTime >= 0) {
			exactTime -= Time.deltaTime;
			time = (int) exactTime;
		}

		if (currentState == DURING_LEVEL && time <= 0) {
			catcher.rb2d.isKinematic = true;
			catcher.rb2d.velocity = Vector2.zero;
			ball.rb2d.isKinematic = true;
			ball.rb2d.velocity = Vector2.zero;
			currentState = AFTER_LEVEL;
			string innerTextStr = "Collected fruits: \t" + scoreCount + "\n";
			innerTextStr += "Wasted fruits: \t\t\t" + crushCount + "\n";
			int levelScore = Mathf.Max (((5 * scoreCount) - crushCount), 0);
			innerTextStr += "Level score: \t\t\t\t" + levelScore + "\n\n";
			TotalScoreS.totalScore += levelScore;
			innerTextStr += "Total score: \t\t\t\t" + TotalScoreS.totalScore;
			if (levelScore < requiredScore) {
				panelCaption.text = "Level Failed";
				innerTextStr = "You need at least " + requiredScore + " score\n"
					+ "to pass this level.\n\n" + innerTextStr;
				failed = true;
			} else {
				panelCaption.text = "Level Complete";
			}
			panelInnerText.text = innerTextStr;
			midPanel.gameObject.SetActive (true);
		} else if (currentState == AFTER_LEVEL) {
			if (Input.GetMouseButtonDown (0)) {
				if (failed || levelNumber == MAX_LEVEL) {
					SceneManager.LoadScene ("Leaderboard");
				} else {
					SceneManager.LoadScene ("Level" + (levelNumber + 1));
				}
			}
		}
	}

	string twoDigited(int num) {
		if (num < 10) {
			return "0" + num;
		}
		return "" + num;
	}

}
