using System;
using System.Runtime.Caching;
using Kreta.Core.Logic;
using Kreta.DataAccessManual;
using Kreta.Naplo.Dao.V3.Naplo;

namespace Kreta.Naplo.BusinessLogic.V3.Intezmeny
{
    internal static class IntezmenySubqueries
    {
        internal static IntezmenyAdatokDao GetIntezmenyAdatokFromCache(string intezmenyAzonosito)
        {
            var cache = MemoryCache.Default;
            var cacheKey = $"{intezmenyAzonosito}_mobileIntezmenyAdatok";

            if (!(cache[cacheKey] is IntezmenyAdatokDao intezmenyAdatok))
            {
                intezmenyAdatok = new IntezmenyAdatokDao();

                Dal.MobileConnection.Run(
                    intezmenyAzonosito,
                    null,
                    h =>
                    {
                        intezmenyAdatok = h.IntezmenyDal().GetIntezmenyIdAktivTanevIdByAzonosito(intezmenyAzonosito).Tables[0].Rows[0].ToDao<IntezmenyAdatokDao>();
                    });

                var policy = new CacheItemPolicy
                {
                    AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddMinutes(20))
                };

                cache.Set(cacheKey, intezmenyAdatok, policy);
            }

            return intezmenyAdatok;
        }

        internal static void RemoveIntezemenyAdatokCache(string intezmenyAzonosito)
        {
            _ = MemoryCache.Default.Remove($"{intezmenyAzonosito}_mobileIntezmenyAdatok");
        }
    }
}