using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Foresight.Data;

namespace IronIntel.Contractor
{
    /// <summary>
    /// 
    /// </summary>
    public class BusinessBase
    {
        public static string NewID()
        {
            return Guid.NewGuid().ToString().ToUpper();
        }

        public static decimal? NegativeToNull(decimal v)
        {
            if (v < 0)
            {
                return null;
            }
            else
            {
                return v;
            }
        }

        public static double? NegativeToNull(double v)
        {
            if (v < 0)
            {
                return null;
            }
            else
            {
                return v;
            }
        }

        public static int? NegativeToNull(int v)
        {
            if (v < 0)
            {
                return null;
            }
            else
            {
                return v;
            }
        }

        public string DbConnectionString { get; private set; }
        public BusinessBase(string dbstr)
        {
            DbConnectionString = dbstr;
        }

        public static void ExecSQL(FIDbAccess db,int retrytimes,string sql, params object[] values)
        {
            int n = 0;
            while (true)
            {
                n++;
                try
                {
                    db.ExecSQL(sql, values);
                    return;
                }
                catch
                {
                    if (n >= retrytimes)
                    {
                        throw;
                    }
                }
                System.Threading.Thread.Sleep(100);
            }
        }

        protected void ExecSQL(string sql, params object[] values)
        {
            FISqlConnection db = new FISqlConnection(DbConnectionString);
            db.ExecSQL(sql, values);
        }

        protected DataTable GetDataTableBySQL(string sql, params object[] values)
        {
            FISqlConnection db = new FISqlConnection(DbConnectionString);
            db.CommandTimeout = 120;
            return db.GetDataTableBySQL(sql, values);
        }

        protected object GetRC1BySQL(string sql, params object[] values)
        {
            FISqlConnection db = new FISqlConnection(DbConnectionString);
            return db.GetRC1BySQL(sql, values);
        }

        protected FISqlTransaction BeginTransaction()
        {
            return new FISqlTransaction(DbConnectionString);
        }
    }
}
