using System;
using System.Data;
using System.Runtime.Caching;
using Kreta.DataAccessManual;

namespace Kreta.BusinessLogic.Classes.MobileApi.Common.Co
{
    public class DefaultConnectionParameters
    {
        private class IntezmenyAdatok
        {
            public int TanevId { get; set; }

            public int IntezmenyId { get; set; }

            public string IntezmenyNev { get; set; }
        }

        public string IntezmenyAzonosito { get; }

        public int TanevId { get; }

        public int IntezmenyId { get; }

        public string IntezmenyNev { get; }

        public int FelhasznaloId { get; }

        public DefaultConnectionParameters(MobileUser mobileUser)
        {
            this.FelhasznaloId = mobileUser.ActualUserId;
            this.IntezmenyAzonosito = mobileUser.InstituteCode;
            this.TanevId = mobileUser.SchoolYearId;
            var intezmenyAdatok = GetIntezmenyAdatokFromCache();
            this.IntezmenyId = intezmenyAdatok.IntezmenyId;
            this.IntezmenyNev = intezmenyAdatok.IntezmenyNev;
        }

        private IntezmenyAdatok GetIntezmenyAdatokFromCache()
        {
            var cache = MemoryCache.Default;
            string cacheKey = $"{IntezmenyAzonosito}_mobileIntezmenyAdatok";
            var intezmenyAdatok = cache[cacheKey] as IntezmenyAdatok;
            if (intezmenyAdatok == null)
            {
                intezmenyAdatok = GetIntezmenyAdatok();

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

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

            return intezmenyAdatok;
        }

        private IntezmenyAdatok GetIntezmenyAdatok()
        {
            return Dal.MobileConnection.Run(IntezmenyAzonosito, TanevId, h =>
            {
                var intezmenyAdatok = h.IntezmenyDal().GetIntezmenyIdAndNevByAzonosito(IntezmenyAzonosito);
                var returnIntezmenyAdatokObject = new IntezmenyAdatok
                {
                    IntezmenyId = intezmenyAdatok.Tables[0].Rows[0].Field<int>("Id"),
                    IntezmenyNev = intezmenyAdatok.Tables[0].Rows[0].Field<string>("Nev")
                };

                return returnIntezmenyAdatokObject;
            }, FelhasznaloId);
        }
    }
}