using System;
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using TMPro;
using Random = UnityEngine.Random;

public enum ELeaderboardState
{
    show_player_rank = 0,
    show_top_10,
}

public class UI_Leaderboards : TM_UI_Base
{
    public GameObject prefab_RankEntry;
    public GameObject FirstLeaderboardEntryAnchor;
    public Canvas myCanvas;
    public float fSpaceBetweenEntries;

    public ELeaderboardState state;
    public List<TM_LeaderboardEntry> currentLeaderboardEntries;

    public Button button_TopScore;
    public Button button_PlayerScore;
    public TextMeshProUGUI text_Loading;

    public int iPlayerRankOnLeaderboards;

    GameObject[] rankEntries;
    public int iMaxDisplay = 15;

    bool bLeaderboardsDirty;

    public int iCurrentFirstEntry = 0;

    private TextMeshProUGUI glowyText_name;
    private TextMeshProUGUI glowyText_rank;
    private TextMeshProUGUI glowyText_score;


    private GameManager theGame;
    private float fGlowyTimeIndex;

    public AudioClip clip_click;

    void Awake()
    {
        theGame = GameObject.Find("GameManager").GetComponent<GameManager>();
    }

    public override void Start()
    {
        base.Start();
    }

    public override void TurnOn()
    {
        base.TurnOn();
        currentLeaderboardEntries = TM_LeaderboardManager.top100LeaderboardEntries;
        state = ELeaderboardState.show_top_10;
        TM_LeaderboardManager.AddOnLeaderboardDirtyFunction(TellUIAboutDirt);
        TM_LeaderboardManager.GetLeaderboardsFromWeb();
    }

    public void OnClick_ShowTopScores()
    {
        currentLeaderboardEntries = TM_LeaderboardManager.top100LeaderboardEntries;
        state = ELeaderboardState.show_top_10;
        bLeaderboardsDirty = true;

        button_TopScore.GetComponentInChildren<TextMeshProUGUI>().color = Color.yellow;
        button_PlayerScore.GetComponentInChildren<TextMeshProUGUI>().color = Color.white;

        
        TM_AudioManager.PlayClip(clip_click);
    }

    public void OnClick_ShowPlayerScores()
    {
        currentLeaderboardEntries = TM_LeaderboardManager.nearPlayerLeaderboardEntries;
        state = ELeaderboardState.show_player_rank;

        iCurrentFirstEntry = 0;
        bLeaderboardsDirty = true;

        button_TopScore.GetComponentInChildren<TextMeshProUGUI>().color = Color.white;
        button_PlayerScore.GetComponentInChildren<TextMeshProUGUI>().color = Color.yellow;

        TM_AudioManager.PlayClip(clip_click);

    }

    public void OnClick_Back()
    {
        if (state == ELeaderboardState.show_top_10)
        {
            iCurrentFirstEntry -= iMaxDisplay;
            if (iCurrentFirstEntry < 0)
                iCurrentFirstEntry = 0;

            SetLeaderboardsDirty();
            TM_AudioManager.PlayClip(clip_click);

        }
    }

    public void OnClick_Forward()
    {
        if (state == ELeaderboardState.show_top_10)
        {
            iCurrentFirstEntry += iMaxDisplay;
            if (iCurrentFirstEntry > currentLeaderboardEntries.Count - iMaxDisplay)
                iCurrentFirstEntry = currentLeaderboardEntries.Count - iMaxDisplay;

            SetLeaderboardsDirty();
            TM_AudioManager.PlayClip(clip_click);

        }

    }

    public void OnClick_Exit()
    {
        //Debug_SendLeaderboardScores(20);
        TurnOff();
        theGame.ChangeGameState(EGameState.attract_screen);
        TM_AudioManager.PlayClip(clip_click);

    }

    public override void Update()
    {
        fGlowyTimeIndex += Time.deltaTime * 0.5f;
        if (fGlowyTimeIndex > 1.0f)
            fGlowyTimeIndex -= 1.0f;

        if (rankEntries == null)
            rankEntries = new GameObject[iMaxDisplay];

        if (bFirstUpdate)
        {
            TurnOff();
            bFirstUpdate = false;
        }

        if (bLeaderboardsDirty)
        {
            if (!TM_LeaderboardManager.bWaitingForLeaderboards)
            {
                text_Loading.gameObject.SetActive(false);
                UpdateLeaderboards();
            }
            else
            {
                text_Loading.gameObject.SetActive(true);
            }
        }

        if (glowyText_name != null)
        {
            Color glowColor = new Color(0.8f + (Mathf.Sin(fGlowyTimeIndex * 6.28f) * 0.1f), 0.0f, 0.0f);
            glowyText_name.color = glowColor;
            glowyText_rank.color = glowColor;
            glowyText_score.color = glowColor;
        }
    }

    public void TellUIAboutDirt()
    {
        bLeaderboardsDirty = true;
    }

    public void UpdateLeaderboards()
    {
        if (currentLeaderboardEntries == null)
        {
            currentLeaderboardEntries = TM_LeaderboardManager.top100LeaderboardEntries;
            Debug.Log("CurrentLeaderboardEntries is " + currentLeaderboardEntries);
            return;
        }

        //Reset glowy labels
        if (glowyText_name != null)
        {
            Color glowColor = Color.white;
            glowyText_name.color = glowColor;
            glowyText_rank.color = glowColor;
            glowyText_score.color = glowColor;
        }

        glowyText_name = null;
        glowyText_rank = null;
        glowyText_score = null;

        if (iCurrentFirstEntry > currentLeaderboardEntries.Count)
            iCurrentFirstEntry = currentLeaderboardEntries.Count - iMaxDisplay;
        if (iCurrentFirstEntry < 0)
            iCurrentFirstEntry = 0;

        float xPixelPos = FirstLeaderboardEntryAnchor.transform.position.x;
        int idx = 0;
        Debug.Log("Updating leaderboards! Starting at pos " + iCurrentFirstEntry + " with " + currentLeaderboardEntries.Count + " entries.");
        for (int t = iCurrentFirstEntry; t < iCurrentFirstEntry + iMaxDisplay && t < currentLeaderboardEntries.Count; t++)
        {
            GameObject newEntry = rankEntries[idx];
            if (newEntry == null)
            {
                newEntry = Instantiate<GameObject>(prefab_RankEntry);
                rankEntries[idx] = newEntry;
                newEntry.transform.parent = myCanvas.transform;
            }

            Vector3 v = FirstLeaderboardEntryAnchor.transform.position;
            v.y -= idx * fSpaceBetweenEntries;
            newEntry.transform.position = v;

            TextMeshProUGUI txtName = newEntry.transform.FindChild("Text_Name").gameObject.GetComponent<TextMeshProUGUI>();
            TextMeshProUGUI txtRank = newEntry.transform.FindChild("Text_Rank").gameObject.GetComponent<TextMeshProUGUI>();
            TextMeshProUGUI txtScore = newEntry.transform.FindChild("Text_Score").gameObject.GetComponent<TextMeshProUGUI>();

            txtRank.text = currentLeaderboardEntries[t].iRank.ToString();
            txtScore.text = currentLeaderboardEntries[t].iVal1.ToString();
            txtName.text = currentLeaderboardEntries[t].strName;

            if (txtName.text == theGame.strPlayerHighScoreName)
            {
                glowyText_name = txtName;
                glowyText_rank = txtRank;
                glowyText_score = txtScore;
            }

            idx++;
        }

        //clean up unused ones
        for (int t = idx; t < rankEntries.Count(); t++)
        {
            GameObject newEntry = rankEntries[t];
            if (newEntry == null)
                continue;

            TextMeshProUGUI txtName = newEntry.transform.FindChild("Text_Name").gameObject.GetComponent<TextMeshProUGUI>();
            TextMeshProUGUI txtRank = newEntry.transform.FindChild("Text_Rank").gameObject.GetComponent<TextMeshProUGUI>();
            TextMeshProUGUI txtScore = newEntry.transform.FindChild("Text_Score").gameObject.GetComponent<TextMeshProUGUI>();

            txtRank.text = null;
            txtScore.text = null;
            txtName.text = null;
        }

        bLeaderboardsDirty = false;
    }

    public void SetLeaderboardsDirty()
    {
        bLeaderboardsDirty = true;
    }
}
