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

namespace RudderSdk.Unity.Samples
{
  public class AuthenticationSample : MonoBehaviour
  {
    [SerializeField] string nickname = "Player";
    [SerializeField] string region = "global";
    [SerializeField] string language = "en";

    readonly SamplePage _page = new SamplePage(
      "Authentication",
      "Initialize the SDK, sign in with the device id, then load the player profile.");

    void OnGUI()
    {
      _page.Draw(() =>
      {
        GUILayout.BeginHorizontal();
        _page.Label("Nickname");
        nickname = GUILayout.TextField(nickname, GUILayout.MaxWidth(200f));
        GUILayout.EndHorizontal();

        GUILayout.BeginHorizontal();
        if (_page.Button("Login with device"))
          _page.Run(this, Login);
        if (_page.Button("Load profile"))
          _page.Run(this, LoadProfile);
        if (_page.Button("Logout"))
          Logout();
        GUILayout.EndHorizontal();
      });
    }

    async Task Login()
    {
      var client = Rudder.Initialize();
      _page.Log("Auth.LoginWithDeviceAsync(" + region + ", " + language + ", " + nickname + ")");
      await client.Auth.LoginWithDeviceAsync(region, language, nickname);
      _page.SetStatus("Signed in");
      await LoadProfile();
    }

    async Task LoadProfile()
    {
      var client = Rudder.Initialize();
      _page.Log("Player.GetProfileAsync()");
      var profile = await client.Player.GetProfileAsync();
      var player = profile?.Player;
      var text = new StringBuilder();
      text.AppendLine("Player id: " + (player?.Id ?? "—"));
      text.AppendLine("Nickname: " + (player?.Nickname ?? "—"));
      text.AppendLine("Region: " + (player?.Region ?? "—"));
      text.AppendLine("Language: " + (player?.Language ?? "—"));
      if (profile?.Wallets == null || profile.Wallets.Count == 0)
      {
        text.Append("Wallets: none");
      }
      else
      {
        text.Append("Wallets:");
        foreach (var wallet in profile.Wallets)
          text.Append("\n  " + wallet.Balance + " " + wallet.Currency);
      }

      _page.SetOutput(text.ToString());
      _page.SetStatus("Profile loaded");
    }

    void Logout()
    {
      if (Rudder.State != RudderState.Ready)
      {
        _page.SetStatus("SDK is not initialized.", true);
        return;
      }

      Rudder.Client.Auth.Logout();
      _page.SetOutput(string.Empty);
      _page.SetStatus("Signed out");
      _page.Log("Auth.Logout()");
    }
  }
}
