using System.Collections.Concurrent;

#pragma warning disable IDE0130 // Namespace does not match folder structure
namespace ArmaRAMDb
#pragma warning restore IDE0130 // Namespace does not match folder structure
{
    internal class KeyValueStore
    {
        private static readonly ConcurrentDictionary<string, string> _keyValues = RAMDb._keyValues;

        public static async Task GetAsync(string key, string function, string uniqueId, string entity = null, string call = "false", int buffersize = Main.ARDB_BUFFERSIZE)
        {
            if (string.IsNullOrEmpty(key) || string.IsNullOrEmpty(function))
            {
                Main.Log($"ArmaRAMDb 'key' or 'function' cannot be empty", "debug");
                return;
            }

            await Task.Yield();

            string value = _keyValues.TryGetValue(key, out string data) ? data : string.Empty;
            Main.Log($"GetValue: {key} - Value: {value}", "debug");
            
            Utils.CheckByteCount(uniqueId, value, function, entity, Convert.ToBoolean(call), buffersize);
        }

        public static async Task SetAsync(string key, string value)
        {
            await Task.Yield();

            if (value.StartsWith('[') && value.EndsWith(']'))
            {
                _keyValues.AddOrUpdate(key, value, (_, _) => value);
            }
            else
            {
                _keyValues.AddOrUpdate(key, $"[\"{value}\"]", (_, _) => $"[\"{value}\"]");
            }
            
            Main.Log($"SetValue: {key} - Value: {value}", "debug");
        }

        public static async Task DeleteAsync(string key)
        {
            await Task.Yield();
            var result = _keyValues.TryRemove(key, out _);
            Main.Log($"DeleteValue: {key} - Success: {result}", "debug");
        }
    }
}