using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LJLib.SQLEX
{
    public class TransactionGroup : IDisposable
    {
        private List<LJTransactionScope> _transactions;

        public TransactionGroup(IEnumerable<SqlCommand> cmds)
        {
            _transactions = new List<LJTransactionScope>();
            foreach (var cmd in cmds)
            {
                if (cmd == null)
                {
                    continue;
                }

                if (cmd.Connection == null)
                {
                    continue;
                }

                if (cmd.Connection.State != ConnectionState.Open)
                {
                    continue;
                }

                _transactions.Add(new LJTransactionScope(cmd));
            }
        }
        
        public void Commit()
        {
            foreach (var ts in _transactions)
            {
                try
                {
                    ts.Complete();
                }
                catch (Exception e)
                {
                    Trace.Write(e);
                }
            }
        }

        public void Dispose()
        {
            foreach (var ts in _transactions)
            {
                try
                {
                    ts.Dispose();
                }
                catch (Exception e)
                {
                    Trace.Write(e);
                }
            }
        }
    }
}
