using Autofac;
using Microsoft.AspNetCore.Http;
using Mall.DataAccess;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Mall.DataHelper
{
    /// <summary>
    /// 数据访问帮助类
    /// </summary>
    public class Helper
    {
        /// <summary>
        /// 自己实现可配置
        /// </summary>
        public bool EnabledDbSession { get { return false; } }

        /// <summary>
        ///  容器
        /// </summary>
        public static IContainer IC { get; set; }

        /// <summary>
        /// 数据连接事务的Session接口
        /// </summary>
        /// <param name="connkey"></param>
        /// <returns></returns>
        public static IDBSession GetPerHttpRequestDBSession(string connkey = "DefaultConnection")
        {
            IDBSession dbSession;
            if (System.WebHttpContext.HttpContext.httpCurrent.Request.HttpContext.Items["IDBSession_" + connkey] != null)
            {
                dbSession = System.WebHttpContext.HttpContext.httpCurrent.Request.HttpContext.Items["IDBSession_" + connkey] as IDBSession;
            }
            else
            {
                if (connkey == "DefaultConnection")
                {
                    dbSession = Helper.IC.Resolve<IDBSession>();
                }
                else
                {
                    dbSession = Helper.IC.ResolveNamed<IDBSession>(connkey);
                }
                System.WebHttpContext.HttpContext.httpCurrent.Request.HttpContext.Items["IDBSession_" + connkey] = dbSession;
                System.WebHttpContext.HttpContext.httpCurrent.Request.HttpContext.Items["IDBSession_Keys"] += connkey + ",";
            }
            return dbSession;
        }

        /// <summary>
        /// 释放DBSession
        /// </summary>
        public void DisposePerHttpRequestDBSession()
        {
            string IDBSession_Keys = (System.WebHttpContext.HttpContext.httpCurrent.Request.HttpContext.Items["IDBSession_Keys"] ?? "").ToString();
            if (IDBSession_Keys.Length > 0)
            {
                foreach (string connkey in IDBSession_Keys.Split(','))
                {
                    if (!string.IsNullOrEmpty(connkey))
                    {
                        if (System.WebHttpContext.HttpContext.httpCurrent.Request.HttpContext.Items["IDBSession_" + connkey] is IDBSession dbSession)
                        {
                            dbSession.Dispose();
                        }
                    }
                }
            }
        }
    }
}
