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

namespace RudderSdk.Unity.Samples
{
  public class RemoteConfigSample : MonoBehaviour
  {
    [SerializeField] string nickname = "Player";
    [SerializeField] string region = "global";
    [SerializeField] string language = "en";
    [SerializeField] string roundSecondsKey = "demo_round_seconds";
    [SerializeField] string playerSpeedKey = "demo_player_speed";

    readonly SamplePage _page = new SamplePage(
      "Remote Config",
      "Load the project's remote config cache, then read typed values with fallbacks.");

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

    void OnGUI()
    {
      _page.Draw(() =>
      {
        if (_page.Button("Reload"))
          _page.Run(this, Load);
      });
    }

    async Task Load()
    {
      var client = Rudder.Initialize();
      _page.Log("RemoteConfig.LoadAsync()");
      var configs = await client.RemoteConfig.LoadAsync();

      var roundSeconds = client.RemoteConfig.Get(roundSecondsKey, 150f);
      var playerSpeed = client.RemoteConfig.Get(playerSpeedKey, 260f);

      var text = new StringBuilder();
      text.AppendLine(roundSecondsKey + " = " + roundSeconds);
      text.AppendLine(playerSpeedKey + " = " + playerSpeed);
      text.AppendLine();
      text.AppendLine("All keys (" + configs.Count + "):");
      foreach (var pair in configs)
        text.AppendLine("  " + pair.Key + " = " + pair.Value.Value + " (" + pair.Value.ValueType + ")");

      _page.SetOutput(text.ToString());
      _page.SetStatus("Loaded " + configs.Count + " config(s)");
    }
  }
}
