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

public class LeaderboardDisplayObject
{
    public TextMeshProUGUI txtRank;
    public TextMeshProUGUI txtName;
    public TextMeshProUGUI txtScore;
}

public class UI_Leaderboards : TM_UI_Base 
{
    public TM_LeaderboardManager_Dreamlo theLeaderboards;
    private IList<TM_LeaderboardEntry> currentEntries;

    private string strID = "";
    private string strScore = "";

    private string strRangeAbove = "";
    private string strRangeBelow = "";

    [Header("Display Info")]
    public int NumRanksOnScreen;
    public GameObject LeaderboardRankingsAnchorObject;
    public GameObject Prefab_DisplayObject;
    private List<LeaderboardDisplayObject> listDisplayObjects;
    public TextMeshProUGUI txtLoadingLabel;
    public EventSystem eventSystem;
    public GameObject StartFocusObject;

    private GameManager theGame;

	// Use this for initialization
	void Start () 
    {
		theGame = GameManager.GetGame();
	}

    public override void TurnOn()
    {
        base.TurnOn();
        if (!bFirstUpdate)
        {
            theLeaderboards.Initialize(theGame.GetHighScoreName());
            RequestEntries();
        }
        eventSystem.SetSelectedGameObject(StartFocusObject);
    }

    // Update is called once per frame
	void Update () 
    {
        if (bFirstUpdate)
        {
            InitLeaderboardObjects();
            bFirstUpdate = false;
            TurnOff();
            return;
        }

        bool bNotReady = true;
        if (theLeaderboards.GetDataState() == ELeaderboardDataState.no_data_ready)
        {
            //try?
            theLeaderboards.RequestLeaderboardEntries(1, 15);
        }
        else if (theLeaderboards.GetDataState() == ELeaderboardDataState.ready )
        {
            bNotReady = false;
            currentEntries = theLeaderboards.GetLoadedLeaderboardEntries();
            if (currentEntries != null)
            {
                UpdateEntryObjects();
                txtLoadingLabel.text = "";
            }
            else
            {
                txtLoadingLabel.text = "Empty?";
            }
        }

        if( bNotReady )
        {
            if (listDisplayObjects != null)
            {
                for (int t = 0; t < listDisplayObjects.Count; t++)
                {
                    LeaderboardDisplayObject ld = listDisplayObjects[t];
                    ld.txtRank.transform.parent.gameObject.SetActive(false);
                }
            }
            txtLoadingLabel.text = theLeaderboards.GetDataState().ToString();
            for (int t = 0; t < Mathf.PingPong(Time.time * 2.0f, 3.0f); t++)
            {
                txtLoadingLabel.text += ".";
            }
        }
	}

    void UpdateEntryObjects()
    {
        for (int t = 0; t < listDisplayObjects.Count; t++)
        {
            Color drawColor = Color.white;
            LeaderboardDisplayObject ld = listDisplayObjects[t];

            if (t >= currentEntries.Count)
            {
                ld.txtRank.transform.parent.gameObject.SetActive(false);
                continue;
            }

            if (currentEntries[t].strName == theGame.GetHighScoreName())
            {
                drawColor = Color.Lerp(theGame.color_Gold, theGame.color_Red, Mathf.PingPong(Time.time, 1.0f));
            }
            ld.txtRank.transform.parent.gameObject.SetActive(true);
            ld.txtRank.text = currentEntries[t].iRank.ToString();
            ld.txtName.text = currentEntries[t].strName;
            ld.txtScore.text = currentEntries[t].iScore.ToString();

            ld.txtRank.color = drawColor;
            ld.txtName.color = drawColor;
            ld.txtScore.color = drawColor;
        }
    }

    void InitLeaderboardObjects()
    {
        if (listDisplayObjects == null)
        {
            listDisplayObjects = new List<LeaderboardDisplayObject>();
            for (int t = 0; t < NumRanksOnScreen; t++)
            {
                GameObject go = Instantiate(Prefab_DisplayObject);
                go.transform.SetParent(LeaderboardRankingsAnchorObject.transform, false);

                LeaderboardDisplayObject ld = new LeaderboardDisplayObject();
                ld.txtRank = go.transform.FindChild("txt_rank").GetComponent<TextMeshProUGUI>();
                ld.txtScore = go.transform.FindChild("txt_score").GetComponent<TextMeshProUGUI>();
                ld.txtName = go.transform.FindChild("txt_name").GetComponent<TextMeshProUGUI>();

                RectTransform rt = go.transform as RectTransform;
                Vector2 vPos = new Vector2(0, t * -32);
                rt.anchoredPosition = vPos;

                listDisplayObjects.Add(ld);
            }

        }
    }

    public void RequestEntries()
    {
        theLeaderboards.RequestLeaderboardEntries(1, 15);
    }

    public void OnClick_TopScores()
    {
        if (theLeaderboards.GetDataState() == ELeaderboardDataState.ready || theLeaderboards.GetDataState() == ELeaderboardDataState.player_rank_unknown)
        {
            theLeaderboards.RequestLeaderboardEntries(1,15);
        }
    }

    public void OnClick_PlayerScores()
    {
        if (theLeaderboards.GetDataState() == ELeaderboardDataState.ready && theLeaderboards.HasPlayerRank() )
        {
            theLeaderboards.RequestLeaderboardEntriesNearPlayer(3, 15);
        }
    }

    public void OnClick_Exit()
    {
        TurnOff();
        theGame.SetGameState(EGameState.attract);
    }

    public void SubmitHighScore(string name, int score)
    {
        //this won't do anything if the name hasn't changed.
        theLeaderboards.ChangePlayerID(name);

        //up we go!
        theLeaderboards.SendNewEntry(score);

        //Get more datas 
        theLeaderboards.RequestLeaderboardEntriesNearPlayer(3,15);
    }

}
