using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using RudderSdk.Unity;

namespace RudderSdk.Unity.Samples
{
  public class LeaderboardsSample : MonoBehaviour
  {
    [SerializeField] string nickname = "Player";
    [SerializeField] string region = "global";
    [SerializeField] string language = "en";
    [SerializeField] string slug = "cozy-collector-score";

    readonly SamplePage _page = new SamplePage(
      "Leaderboards",
      "Submit a score to a board by slug, then list the top entries.");

    string _scoreText = "10";

    void Start()
    {
      _page.Run(this, async () =>
      {
        await Rudder.Initialize().Auth.LoginWithDeviceAsync(region, language, nickname);
        _page.Log("Signed in");
        await List();
      });
    }

    void OnGUI()
    {
      _page.Draw(() =>
      {
        GUILayout.BeginHorizontal();
        _page.Label("Score");
        _scoreText = GUILayout.TextField(_scoreText, GUILayout.MaxWidth(120f));
        GUILayout.EndHorizontal();

        GUILayout.BeginHorizontal();
        if (_page.Button("Submit"))
          _page.Run(this, Submit);
        if (_page.Button("List top 10"))
          _page.Run(this, List);
        GUILayout.EndHorizontal();
      });
    }

    async Task Submit()
    {
      if (!int.TryParse(_scoreText, out var score))
      {
        _page.SetStatus("Score must be an integer.", true);
        return;
      }

      var client = Rudder.Initialize();
      var board = client.Leaderboards.FindBySlug(slug);
      _page.Log("Leaderboards.FindBySlug(\"" + slug + "\").SubmitAsync(" + score + ")");
      await board.SubmitAsync(score);
      _page.SetStatus("Submitted " + score);
      await List();
    }

    async Task List()
    {
      var client = Rudder.Initialize();
      var board = client.Leaderboards.FindBySlug(slug);
      _page.Log("FindBySlug(\"" + slug + "\").ListAsync(10)");
      var entries = await board.ListAsync(10);

      var text = new StringBuilder();
      text.AppendLine(slug);
      if (entries == null || entries.Count == 0)
      {
        text.Append("No entries yet.");
      }
      else
      {
        foreach (var entry in entries)
        {
          var name = entry.PlayerName;
          if (string.IsNullOrEmpty(name))
            name = entry.PlayerId;
          text.AppendLine("#" + entry.Rank + "  " + name + "  " + entry.Score);
        }
      }

      _page.SetOutput(text.ToString());
      _page.SetStatus("Listed " + (entries == null ? 0 : entries.Count) + " entries");
    }
  }
}
