using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class GameManager : MonoBehaviour
{
    public static GameManager instance;
    void Awake(){
        instance = this;
    }
    public Text txt_money;
    public float moneyMultiplier = 5;
    public Vector3 txtMoneyOffset = Vector2.one;


    public GameObject gameOverPanel;
    public GameObject startPanel;

    public GameObject finishPanel;
    public Text finishedScoreTxt;
    public Transform CheckeredFlag;

    public void StartGame(){
        startPanel.SetActive(false);
    }
    float moneyEarned =0;
    void Update(){
        if(!PlayerController.Started){return;}
        moneyEarned = (PlayerController.t.position.y*moneyMultiplier);
        txt_money.text = "$"+moneyEarned.ToString("n4");

        txt_money.rectTransform.position = Camera.main.WorldToScreenPoint(PlayerController.t.position + txtMoneyOffset);

        if(PlayerController.boosting){
            txt_money.rectTransform.localScale = Vector3.Lerp(txt_money.rectTransform.localScale, Vector3.one * 1.5f, 0.05f);
        }else{
            txt_money.rectTransform.localScale = Vector3.Lerp(txt_money.rectTransform.localScale, Vector3.one , 0.1f);
        }

        if(PlayerController.t.position.y > 120){
            Color curColor = Camera.main.backgroundColor;
            Camera.main.backgroundColor = Color.Lerp(curColor, Color.black, 0.001f);
        }

        if(CheckeredFlag.position.x - PlayerController.t.position.x > 20){
        CheckeredFlag.position = new Vector2(CheckeredFlag.position.x,PlayerController.t.position.y);

        }else if(CheckeredFlag.position.x - PlayerController.t.position.x < 4){
            FinishGame();
        }
    }


    public void gameOver(){
        gameOverPanel.SetActive(true);
        PlayerController.instance.GameOver();
    }
    public static void GameOver(){
        instance.gameOver();
    }


    public void FinishGame(){
        finishPanel.SetActive(true);

        finishedScoreTxt.text = txt_money.text;
        PlayerController.instance.GameOver();

        if(!updatedBest){
            updatedBest=true;

            StartCoroutine(updateBest());
        }
    }

    IEnumerator updateBest(){
        WWWForm form = new WWWForm();
        form.AddField("username", DataManager.Username);
        form.AddField("best", (int)moneyEarned);
        DataManager.best = (int)moneyEarned;

        WWW req = new WWW(DataManager.API_Endpoint +"set_best.php",form);
        yield return req;
        Debug.Log(req.text);
    }

    bool updatedBest = false;

    public void Restart(){
        SceneManager.LoadScene("Game");
    }
    public void Menu(){
        SceneManager.LoadScene("Menu");
    }
}
