using System;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;

namespace LJLib.SQLEX
{
    public sealed class LJTransactionScope : IDisposable
    {
        private bool complete = false;
        private bool ifCreateTran = false;
        private SqlCommand _cmd;
        private string pointName;


        public LJTransactionScope(SqlCommand cmd)
        {
            Trace.Assert(cmd != null && cmd.Connection.State == ConnectionState.Open, "cmd != null && cmd.Connection.State == ConnectionState.Open");
            pointName = Guid.NewGuid().ToString("N");
            _cmd = cmd;
            if (_cmd == null) return;
            if (_cmd.Transaction == null)
            {
                _cmd.Transaction = _cmd.Connection.BeginTransaction(IsolationLevel.ReadUncommitted);
                ifCreateTran = true;
            }
            _cmd.Transaction.Save(pointName);
        }

        public void Complete()
        {
            if (_cmd != null && ifCreateTran)
            {
                _cmd.Transaction.Commit();
            }
            complete = true;
        }

        public void Dispose()
        {
            if (_cmd == null) return;
            if (!complete)
            {
                try
                {
                    _cmd.Transaction.Rollback(pointName);
                    if (ifCreateTran)
                    {
                        _cmd.Transaction.Rollback();
                    }
                }
                catch (Exception ex)
                {
                    Trace.Write(ex);
                }
            }

            if (ifCreateTran)
            {
                using (_cmd.Transaction) { }
                _cmd.Transaction = null;
            }
        }
    }
}
