using System;
using System.Collections.Generic;
using System.Xml;

namespace Kit.Helpers.Repository.Xml
{
    public abstract class EntityXmlPersistentComplexRepositoryWithCache<TEntity, TKey, TRootKey, TFilter, TContextKey> : EntityXmlPersistentComplexRepository<TEntity, TKey, TRootKey, TFilter, TContextKey>
        where TEntity : XmlComplexClass<TKey, TRootKey, TContextKey>
        where TFilter : IXmlComplexFilter<TContextKey, TRootKey, TKey>
    {
        private string _cacheKey;
        protected bool _cacheOn;

        private void CacheInit()
        {
            _cacheKey = this.GetType().FullName;
            _cacheOn = true;
        }

        public EntityXmlPersistentComplexRepositoryWithCache(string elementName) : base(elementName)
        {
            this.CacheInit();
        }

        public EntityXmlPersistentComplexRepositoryWithCache(string path, string elementName) : base(path, elementName)
        {
            this.CacheInit();
        }

        private Dictionary<string, TEntity> GetCacheDictionary()
        {
            return null;
            //HttpContext httpContext = HttpContext.Current;
            //if (httpContext == null) return null;

            //var cacheDictionary = (Dictionary<string, TEntity>)httpContext.Items[_cacheKey];
            //if (cacheDictionary == null)
            //{
            //    cacheDictionary = new Dictionary<string, TEntity>();
            //    httpContext.Items[_cacheKey] = cacheDictionary;
            //}
            //return cacheDictionary;
        }

        private TEntity GetFromCache(string key, Func<TEntity> getAction)
        {
            TEntity entity = null;
            if (_cacheOn)
            {
                Dictionary<string, TEntity> cacheDictionary = this.GetCacheDictionary();
                if (cacheDictionary != null)
                {
                    entity = cacheDictionary.GetByKey(key);
                    if (entity == null)
                    {
                        entity = getAction();
                        cacheDictionary.SetByKey(key, entity);
                    }
                }
            }
            return entity ?? getAction();
        }

        public override TEntity Get(XmlDocument db, TKey key)
        {
            string projectGuid = db.DocumentElement.GetValueAttribute("guid", string.Empty);
            string cacheKey = "{0}_{1}".ApplyFormat(projectGuid, key);

            return this.GetFromCache(cacheKey, () => base.Get(db, key));
        }

        public TEntity Get1(XmlNode xmlNode, TKey key)
        {
            TEntity entity = this.ConvertToEntity(xmlNode);
            return entity;
        }
    }
}
