﻿using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json.Linq;
using System;

namespace Wicture.DbRESTFul.Cache
{
    /// <summary>
    /// Memory 缓存实现。
    /// </summary>
    public class MemoryCacheProvider : ICacheProvider
    {
        private static IMemoryCache memoryCache;

        public event EventHandler OnError;

        public static string Name { get; } = "memory";

        public MemoryCacheProvider(IMemoryCache cache)
        {
            memoryCache = cache;
        }

        public void Set(string key, object data, int expirationInSeconds)
        {
            try
            {
                memoryCache.Set(key, data, DateTime.UtcNow.AddSeconds(expirationInSeconds));
            }
            catch (Exception ex)
            {
                LoggerManager.Logger.LogError(ex, $"Set Cache failed for key: `{key}`");
                OnError?.Invoke(this, null);
            }
        }

        public JToken Get(string key)
        {
            try
            {
                var result = memoryCache.Get(key);
                if (result == null) return null;
                return (result is JToken) ? (result as JToken) : JToken.FromObject(result);
            }
            catch (Exception ex)
            {
                LoggerManager.Logger.LogError(ex, $"Get Cache failed for key: `{key}`");
                OnError?.Invoke(this, null);
                return null;
            }
        }

        public void Set(string key, object data)
        {
            try
            {
                memoryCache.Set(key, data);
            }
            catch (Exception ex)
            {
                LoggerManager.Logger.LogError(ex, $"Set Cache failed for key: `{key}`");
                OnError?.Invoke(this, null);
            }
        }

        public void Remove(string key)
        {
            try
            {
                memoryCache.Remove(key);
            }
            catch (Exception ex)
            {
                LoggerManager.Logger.LogError(ex, $"Remove Cache failed for key: `{key}`");
                OnError?.Invoke(this, null);
            }
        }
    }
}
