using System;
using Kreta.Core;
using Kreta.Ellenorzo.Domain.VN.Felhasznalo.Tanulo;
using Kreta.Framework.Caching;

namespace Kreta.BusinessLogic.Caching
{
    public class TanuloAdatlapCache : GenericCache<object>
    {
        private static readonly string TanuloAdatlapCacheKeyPrefix = $"{Constants.Cache.CacheKeyPrefix}TanuloAdatlapCache_";

        public TanuloAdatlapCache(Framework.Caching.CacheManager cacheManager) : base(cacheManager, nameof(TanuloAdatlapCache))
        {
        }

        public TanuloAdatResponse GetOrAddTanuloAdatlap(int userId, string instituteCode, Func<TanuloAdatResponse> value)
        {
            return GetOrAddValue(TanuloAdatlapCacheKeyPrefix, userId, instituteCode, value);
        }

        public void RemoveTanuloAdatlap(int userId, string instituteCode)
        {
            RemoveValue(TanuloAdatlapCacheKeyPrefix, userId, instituteCode);
        }

        protected string GetCacheKey(string keyPrefix, int userId, string instituteCode)
        {
            return $"{keyPrefix}{instituteCode}.{userId}";
        }

        protected T GetOrAddValue<T>(string cacheKeyPrefix, int userId, string instituteCode, Func<T> valueFactory) where T : class
        {
            string key = GetCacheKey(cacheKeyPrefix, userId, instituteCode);
            object value = GetOrAdd(key, _ => valueFactory());

            return (T)value;
        }

        protected void RemoveValue(string cacheKeyPrefix, int userId, string instituteCode)
        {
            string key = GetCacheKey(cacheKeyPrefix, userId, instituteCode);
            Remove(key);
        }
    }
}