#nullable enable

using System;
using UnityEngine;

namespace HyperstoneSdk
{
    public interface IHyperstoneStorage
    {
        string? GetUid();
        void SetUid(string uid);
        void ClearUid();        
        string? GetJsonConfig();
        void SetJsonConfig(string? jsonConfig);
        void LoadMetricsReplacingInto(MetricsContainer buffer);
        void SaveMetrics(MetricsContainer buffer);        
        void Clear();
    }


    // Serializable so that class can survive domain reload
    [Serializable]
    class PlayerPrefsHyperstoneStorage : IHyperstoneStorage
    {
        private string _uid;
        private string _config;
        private string _metrics;

        public PlayerPrefsHyperstoneStorage(string appId)
        {
            _uid = $"xp-uid-{appId}";
            _config = $"xp-config-{appId}";
            _metrics = $"xp-metrics-{appId}";
        }

        public string? GetUid()
        {
            return PlayerPrefs.GetString(_uid);
        }

        public void SetUid(string uid)
        {
            PlayerPrefs.SetString(_uid, uid);
        }

        public void ClearUid()
        {
            PlayerPrefs.DeleteKey(_uid);
        }

        public string? GetJsonConfig()
        {
            return PlayerPrefs.GetString(_config);
        }

        public void SetJsonConfig(string? jsonConfig)
        {
            PlayerPrefs.SetString(_config, jsonConfig);
        }

        public void LoadMetricsReplacingInto(MetricsContainer buffer)
        {
            buffer.Clear();
            var bufferString = PlayerPrefs.GetString(_metrics);
            if (string.IsNullOrEmpty(bufferString))
            {
                return;
            }

            buffer.AddFrom(bufferString);
        }

        public void SaveMetrics(MetricsContainer buffer)
        {
            PlayerPrefs.SetString(_metrics, buffer.ToString());
        }
        public void Clear()
        {
            PlayerPrefs.DeleteKey(_uid);
            PlayerPrefs.DeleteKey(_config);
            PlayerPrefs.DeleteKey(_metrics);
        }
    }
}
