using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Cmdjy.Dal.Tables;
using System.Data.Entity;
using Cmdjy.Bll;

namespace Cmdjy.Dal.Queryes
{
    public interface IHisPrescriptionQuery:IDbQuery<HisPrescriptionInfo> { }

    public class HisPrescriptionQuery:IHisPrescriptionQuery
    {
        public Lazy<ICache> Cache { get; set; }

        public HisPrescriptionQuery() {
            this.Cache = new Lazy<ICache>(() => CacheFactory.Cache);
        }

        public IEnumerable<HisPrescriptionInfo> GetAll() {
            using(var db = DbContextFactory.CreateDbContext()) {
                return db.PrescriptionInfos.ToList();
            }
        }

        public HisPrescriptionInfo GetOne<TKey>(TKey id) {
            var key = getKey(id.ToString());
            var val = this.Cache.Value.GetData<HisPrescriptionInfo>(key);
            if(val == null) {
                using(var db = DbContextFactory.CreateDbContext()) {
                    val = db.PrescriptionInfos.Find(id);
                    if(val != null) this.Cache.Value.SetData(key,val);
                }
            }
            return val;
        }

        public void Insert(HisPrescriptionInfo obj) {
            using(var db = DbContextFactory.CreateDbContext()) {
                db.Entry(obj).State = EntityState.Added;
                db.SaveChanges();
            }
            var key = getKey(obj.Id.ToString());
            this.Cache.Value.SetData(key,obj);
        }

        IQueryable<HisPrescriptionInfo> IDbQuery<HisPrescriptionInfo>.GetQuery(DjyDbContext db) {
            return db.PrescriptionInfos.AsQueryable();
        }

        private string getKey(string id) {
            return $"Db:HisPrescriptionInfo:Id:{id}";
        }
    }
}