using System.Threading.Tasks;
using RudderSdk.Core.Models.Storage;
using UnityEngine;
using RudderSdk.Unity;

namespace RudderSdk.Unity.Samples
{
  public class StorageSample : MonoBehaviour
  {
    [SerializeField] string nickname = "Player";
    [SerializeField] string region = "global";
    [SerializeField] string language = "en";
    [SerializeField] string storageType = "sample_save";
    [SerializeField] string storageId = "main";

    readonly SamplePage _page = new SamplePage(
      "Storage",
      "Read and write a player storage item. Data is an opaque JSON string.");

    string _data = "{\"bestScore\":0}";

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

    void OnGUI()
    {
      _page.Draw(() =>
      {
        _page.Label("Data");
        _data = GUILayout.TextArea(_data, GUILayout.MinHeight(72f));
        GUILayout.BeginHorizontal();
        if (_page.Button("Load"))
          _page.Run(this, Load);
        if (_page.Button("Save"))
          _page.Run(this, Save);
        if (_page.Button("Delete type"))
          _page.Run(this, Delete);
        GUILayout.EndHorizontal();
      });
    }

    async Task Load()
    {
      var client = Rudder.Initialize();
      _page.Log("Storage.GetAsync(type: " + storageType + ")");
      var response = await client.Storage.GetAsync(storageType);
      StorageItem item = null;
      if (response?.Items != null)
      {
        foreach (var candidate in response.Items)
        {
          if (candidate.Id == storageId)
          {
            item = candidate;
            break;
          }
        }
      }

      if (item == null)
      {
        _page.SetOutput("No item " + storageType + "/" + storageId + " yet.");
        _page.SetStatus("Empty");
        return;
      }

      _data = item.Data;
      _page.SetOutput("Loaded " + item.Type + "/" + item.Id + "\n" + item.Data);
      _page.SetStatus("Loaded");
    }

    async Task Save()
    {
      var client = Rudder.Initialize();
      _page.Log("Storage.SaveAsync(" + storageType + "/" + storageId + ")");
      await client.Storage.SaveAsync(new[]
      {
        new StorageItem
        {
          Type = storageType,
          Id = storageId,
          Data = _data
        }
      });
      _page.SetOutput("Saved " + storageType + "/" + storageId);
      _page.SetStatus("Saved");
    }

    async Task Delete()
    {
      var client = Rudder.Initialize();
      _page.Log("Storage.DeleteAsync(" + storageType + ")");
      await client.Storage.DeleteAsync(storageType);
      _page.SetOutput("Deleted all items of type " + storageType);
      _page.SetStatus("Deleted");
    }
  }
}
