using System.Linq;
using iiie.CacheControl.DataAccess;
using iiie.CacheControl.DBO;

namespace iiie.CacheControl.Business.OutputCache
{
    public class DbOutputCache : IOutputCache
    {
        public string ConnectionString { get; set; }

        private CacheControlEntities GetDb()
        {
            if (ConnectionString == null)
                return new CacheControlEntities();
            return new CacheControlEntities(ConnectionString);
        }

        public override CacheDbo Get(string key)
        {
            using (var db = GetDb())
            {
                var item = db.T_Cache.FirstOrDefault(x => x.cachekey == key);
                if (item == null)
                    return null;
                return new CacheDbo
                {
                    Date = item.date,
                    ETag = item.etag,
                    Content = item.content,
                    ContentType = item.content_type
                };
            }
        }

        public override void Remove(string key)
        {
            using (var db = GetDb())
            {
                var item = db.T_Cache.FirstOrDefault(x => x.cachekey == key);
                if (item != null)
                {
                    db.T_Cache.Remove(item);
                    db.SaveChanges();
                }
            }
        }

        public override bool Contains(string key)
        {
            using (var db = GetDb())
            {
                return db.T_Cache.Any(x => x.cachekey == key);
            }
        }

        public override void Add(string key, CacheDbo o)
        {
            using (var db = GetDb())
            {
                db.T_Cache.Add(new T_Cache
                {
                    cachekey = key,
                    etag = o.ETag,
                    content = o.Content,
                    date = o.Date,
                    content_type = o.ContentType
                });
                db.SaveChanges();
            }
        }
    }
}
