using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using PlayFab;
using PlayFab.ClientModels;
using UnityEngine.UI;

public class PlayerLeaderboard : MonoBehaviour {

    public TMP_Text rankList;
    public TMP_Text playerList;
    public TMP_Text statList;
    public TMP_Text statName;

    string currentStatisticShown;
    string currentStatisticFullShown;

    public int maxResults = 6;

    string statisticPrefix = "";

    public Color activeLeaderboardColor;
    public Color inactiveLeaderboardColor;
    public Image allTimeButtonImage;
    public Image yearlyButtonImage;

    public void GetLeaderboardAroundPlayer(string statisticName) {
        if (statisticPrefix + statisticName == currentStatisticFullShown)
            return;
        currentStatisticShown = statisticName;
        currentStatisticFullShown = statisticPrefix + statisticName;
        statName.SetText(statisticName);
        if (statisticName == "1st Place Wins")
            statName.SetText("1st Place Wins");
        PlayFabClientAPI.GetLeaderboardAroundPlayer(
            new GetLeaderboardAroundPlayerRequest() { StatisticName = currentStatisticFullShown, MaxResultsCount = maxResults,
                ProfileConstraints = new PlayerProfileViewConstraints() {
                    ShowDisplayName = true,
                    ShowStatistics = true
                }
            },
            UpdateLeaderboardAroundPlayer,
            error => Debug.LogError(error.GenerateErrorReport())
        );
    }

    private void UpdateLeaderboardAroundPlayer(GetLeaderboardAroundPlayerResult obj) {
        List<PlayerLeaderboardEntry> leaderboardEntries = obj.Leaderboard;

        string rankText = "";
        string playerText = "";
        string statText = "";
        foreach (PlayerLeaderboardEntry entry in leaderboardEntries) {
            rankText += 1 + entry.Position + "\n";
            playerText += entry.Profile.DisplayName + "\n";
            List<StatisticModel> statistics = entry.Profile.Statistics;
            foreach(StatisticModel statistic in statistics) {
                if (statistic.Name == currentStatisticFullShown) {
                    statText += statistic.Value + "\n";
                    break;
                }
            }
        }

        rankList.SetText(rankText);
        playerList.SetText(playerText);
        statList.SetText(statText);
    }

    public void SwitchToYearly() {
        statisticPrefix = "Yearly ";
        allTimeButtonImage.color = inactiveLeaderboardColor;
        yearlyButtonImage.color = activeLeaderboardColor;
        GetLeaderboardAroundPlayer(currentStatisticShown);
    }

    public void SwitchToAllTime() {
        statisticPrefix = "";
        allTimeButtonImage.color = activeLeaderboardColor;
        yearlyButtonImage.color = inactiveLeaderboardColor;
        GetLeaderboardAroundPlayer(currentStatisticShown);
    }
}
