using UnityEngine;
using UnityEngine.UI;

public class InGameGUIController : MonoBehaviour {

    public Text currentScore;
    public Text remainingTime;
    public Text collectedApplesGreen;
    public Text collectedApplesYellow;
    public Text collectedApplesRed;
    public Text sessionDoneMessage;
    public Button buttonMainMenu;

    public void Start() {
        ToggleSessionOverVisibility(false);
    }

    public void ToggleSessionOverVisibility(bool visible) {
        sessionDoneMessage.gameObject.SetActive(visible);
        buttonMainMenu.gameObject.SetActive(visible);
    }

    public void OpenMainMenu() {
        Application.LoadLevel("AStartmenu");
    }

    public void UpdateScore(int score) {
        string text
              = Localizer.Instance.GetText(
                             "InGameGUI.CurrentScore", score);
        currentScore.text = text;
    }

    public void UpdateTime() {
        string text
          = Localizer.Instance.GetText("InGameGUI.RemainingTime",
                GameStateManager.Instance.RemainingTimeString);
        remainingTime.text = text;
    }

    public void AppleCollected() {
        UpdateCollectedApples();
    }

    private void UpdateCollectedApples() {
        UpdateApples(AppleCategory.Green, collectedApplesGreen);
        UpdateApples(AppleCategory.Yellow, collectedApplesYellow);
        UpdateApples(AppleCategory.Red, collectedApplesRed);
    }

    private void UpdateApples(AppleCategory category, Text field) {
        GameStateManager gsm = GameStateManager.Instance;

        string key = string.Format(
            "InGameGUI.CollectedApples.{0}",
            category.ToString());

        if (gsm.ApplesCount(category) > 0) {
            string text = Localizer.Instance.GetText(key,
                gsm.CollectedApplesCount(category),
                gsm.ApplesCount(category));
            field.text = text;
        } else {
            field.gameObject.SetActive(false);
        }

    }

    public void GameStateChanged() {
        switch (GameStateManager.Instance.CurrentGameState) {
            case GameState.Playing:
                UpdateCollectedApples();
                break;
            case GameState.PlayerCrashed:
            case GameState.TimedOut: 
                sessionDoneMessage.text
                  = Localizer.Instance.GetText("InGameGUI.GameOver");
                ToggleSessionOverVisibility(true);
                break;
            case GameState.AllApplesCollected:
                sessionDoneMessage.text
                  = Localizer.Instance.GetText("InGameGUI.ApplesDone");
                ToggleSessionOverVisibility(true);
                break;
        }
    }
}
