using DirectService.Tools;
using System;
using System.Data.SqlClient;

namespace LJLib
{
    public class CacheService<TKey, TValue> : ICacheService<TKey, TValue>
    where TValue : class, new()
    {
        private readonly LJCache<TKey, TValue> _cache;
        private readonly ICacheLoader<TKey, TValue> _loader;

        public CacheService(ICacheLoader<TKey, TValue> loader, int cacheMinutes = 120)
        {
            _loader = loader ?? throw new ArgumentNullException(nameof(loader));
            _cache = new LJCache<TKey, TValue> { DefaultAddMinutes = cacheMinutes };
        }

        public TValue Get(SqlCommand cmd, TKey key)
        {
            if (!_cache.TryGetValue(key, out TValue value))
            {
                value = _loader.Load(cmd, key);
                _cache.Add(key, value);
            }
            return ObjectHelper.DeepCopy(value);
        }

        public void Remove(TKey key)
        {
            if (_cache.ContainsKey(key)) _cache.Remove(key);
        }
    }
}
