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

public class GameEndProcessor : MonoBehaviour {
    public TMPro.TextMeshProUGUI YearText = null;

    public GameObject GameEndPanel = null;
    public TMPro.TextMeshProUGUI WinText = null;
    public TMPro.TextMeshProUGUI TreesAtStart = null;
    public TMPro.TextMeshProUGUI TreesDestroyed = null;
    public TMPro.TextMeshProUGUI HousesLost = null;
    public TMPro.TextMeshProUGUI FinalScore = null;
    public TMPro.TextMeshProUGUI TotalScore = null;

    private void Start()
    {
        YearText.text = PlayerStats.NextLevel.ToString();
    }

    public bool WonGame = false;
    void RefreshScores()
    {
        WinText.text = WonGame ? "You survived this year" : "Half the forest burned. Game Over.";
        TreesAtStart.text = GetComponent<TreeProcessor>().TotalTrees.ToString();
        TreesDestroyed.text = GetComponent<TreeProcessor>().TreesDestroyed.ToString();
        HousesLost.text = GetComponent<HouseProcessor>().HousesLost.ToString();

        int computerScore =
            GetComponent<TreeProcessor>().TotalTrees * 5
            - 1 * GetComponent<TreeProcessor>().TreesDestroyed
            - 50 * GetComponent<HouseProcessor>().HousesLost;

        FinalScore.text = computerScore.ToString();

        PlayerStats.TotalScore += computerScore;

        TotalScore.text = PlayerStats.TotalScore.ToString();

        GameEndPanel.SetActive(true);
    }

    public void GameEndButtonPressed()
    {
        if (WonGame)
        {
            PlayerStats.NextLevel = PlayerStats.NextLevel + 1;
            UnityEngine.SceneManagement.SceneManager.LoadScene("CoreGameplayLevel");
        }
        else
        {
            PlayerStats.NextLevel = 0;
            PlayerStats.TotalScore = 0;
            UnityEngine.SceneManagement.SceneManager.LoadScene("IntroScreen");
        }

    }

    // Update is called once per frame
    void Update () {
        if (!GameEndPanel.activeSelf)
        {
            if (GetComponent<TreeProcessor>().PercentTreesDestroyed >= 0.51f)
            {
                WonGame = false;
                RefreshScores();
            }

            if (GetComponent<TreeProcessor>().BurningTrees < 1)
            {
                WonGame = true;
                RefreshScores();
            }
        }
    }
}
