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

public class GameManager : MonoBehaviour
{
    public static GameManager instance;

    public Text scoreText;
    public Text coinScoreText;
    public Text highScoreText;

    public float worldScrollingSpeed = 0.2f;

    public bool inGame;

    public GameObject resetButton;

    private float score;
    private int highScoreValue;

    private int coins;


    void Start()
    {
        if (instance == null) { instance = this; }

        InitializeGame();
    }

    void InitializeGame()
    {
        inGame = true;

        if (PlayerPrefs.HasKey("HighScoreValue"))
        {
            highScoreValue = PlayerPrefs.GetInt("HighScoreValue");
        }
        else
        {
            highScoreValue = 0;
            PlayerPrefs.SetInt("HighScoreValue", 0);
        }

        if (PlayerPrefs.HasKey("Coins"))
        {
            coins = PlayerPrefs.GetInt("Coins");
        }
        else
        {
            coins = 0;
            PlayerPrefs.SetInt("Coins", 0);
        }
    }

    public void GameOver()
    {
        inGame = false;
        resetButton.SetActive(true);

        if ((int)score > highScoreValue)
        {
            highScoreValue = (int)score;
            PlayerPrefs.SetInt("HighScoreValue", highScoreValue);
        }
    }

    void FixedUpdate()
    {
        if (!GameManager.instance.inGame) return;

        score += worldScrollingSpeed;
        UpdateOnScreenScore();
    }
    void UpdateOnScreenScore()
    {
        scoreText.text = score.ToString("0");
        coinScoreText.text = coins.ToString();
        highScoreText.text = highScoreValue.ToString();
    }

    public void RestartGame()
    {
        SceneManager.LoadScene(0);
    }

    public void CoinCollected(int value = 1)
    {
        coins += value;

        PlayerPrefs.SetInt("Coins", coins);
    }
}