using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Caching;

namespace BookDemo.QA
{

    public abstract class BaseCache<T> where T : class, new()
    {
        public delegate void UpdateWithBataBase(T obj);

        private string _cacheKey;
        private T _data;
        //private ICacheStrategy _cache;
        public CacheStrategy Cache { get; set; }
        public int _timeout = 1440;//超时时间，1400分钟为1天。
        public BaseCache(string cacheKey)
        {
            _cacheKey = cacheKey;
            Cache = CacheStrategy.Instance;
        }

        public virtual T Data
        {
            get
            {
                if (_data != null)
                {
                    return _data;
                }
                if (Cache.Get(_cacheKey) == null)
                {
                    this.Update();
                }
                return Cache.Get(_cacheKey) as T;
            }
            set
            {
                if (Data != value)
                {
                    Cache.InsertToCache(_cacheKey, value, _timeout);
                }
            }
        }

        public virtual void SetData(T value, int timeOut, CacheDependency dependencies, UpdateWithBataBase updateWithDatabases)
        {
            Cache.InsertToCache(_cacheKey, value, timeOut, dependencies);
            if (updateWithDatabases != null)
            {
                updateWithDatabases.Invoke(value);
            }
        }

        public virtual void Remove()
        {
            Cache.RemoveFromCache(_cacheKey);
        }

        public abstract T Update();
        public virtual void UpdateToDatabase(T obj)
        {
        }
    }
}
