using XYY.Common.Standard;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace XYY.Core.Standard.Data.Infrastructure
{
    public interface IUnitOfWork : IDisposable
    {
        string ConnectionAddress { get; set; }
        int? CurrentId { get; set; }
        string CurrentName { get; set; }

        int? CustomerId { get; set; }
        IDbConnection Connection { get; set; }
        IDbTransaction Transaction { get; set; }
        List<DataPermission> DataPermission { get; set; }
        void Commit();
        void Rollback();
    }

    public class UnitOfWork : IUnitOfWork
    {

        public string ConnectionAddress { get; set; }

        private enum TransType
        {
            提交事务,
            回滚事务
        }

        public int? CurrentId { get; set; }
        public int? CustomerId { get; set; }
        public string CurrentName { get; set; }
        public IDbConnection Connection { get; set; }
        public IDbTransaction Transaction { get; set; }
        public UnitOfWork(IDbConnection dbConnection, string ConnectionAddress)
        {
            IsCommit = false;
            this.Connection = dbConnection;
            this.ConnectionAddress = ConnectionAddress;
        }

        private void SaveChanges(TransType trans)
        {
            if (!IsCommit && Connection != null && Connection.State == ConnectionState.Open && Transaction != null)
            {
                switch (trans)
                {
                    case TransType.提交事务: Transaction.Commit(); break;
                    case TransType.回滚事务: Transaction.Rollback(); break;
                }
                IsCommit = true;
            }
            if (Connection != null && Connection.State == ConnectionState.Open)
            {
                Connection.Close();
            }
        }

        private bool IsCommit { get; set; }

        public void Commit()
        {
            SaveChanges(TransType.提交事务);
        }

        public void Rollback()
        {
            SaveChanges(TransType.回滚事务);
        }
        public void Dispose()
        {
            Trace.WriteLine("UnitOfWork Dispose");
            //try
            //{
            //    Commit();
            //}
            //catch (Exception)
            //{
            //    Rollback();
            //}
            //finally
            //{
            //    if (Connection.State != ConnectionState.Closed)
            //    {
            //        Connection.Close();
            //    }
            //}
            //Commit();
        }

        public List<DataPermission> DataPermission { get; set; }

    }
}
