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

namespace KstSoft.DBUtility
{
    public abstract class OleDB_Helper
    {
        public static string connectionString = PubConn.ConnectionString;

        public static OleDbDataReader ExecuteReader(string strSQL)
        {
            OleDbDataReader reader2;
            OleDbConnection connection = new OleDbConnection(connectionString);
            OleDbCommand command = new OleDbCommand(strSQL, connection);
            try
            {
                connection.Open();
                reader2 = command.ExecuteReader();
            }
            catch (OleDbException exception)
            {
                throw new Exception(exception.Message);
            }
            return reader2;
        }

        public static OleDbDataReader ExecuteReader(string SQLString, params OleDbParameter[] cmdParms)
        {
            OleDbDataReader reader2;
            OleDbConnection conn = new OleDbConnection(connectionString);
            OleDbCommand cmd = new OleDbCommand();
            try
            {
                PrepareCommand(cmd, conn, null, SQLString, cmdParms);
                OleDbDataReader reader = cmd.ExecuteReader();
                cmd.Parameters.Clear();
                reader2 = reader;
            }
            catch (OleDbException exception)
            {
                throw new Exception(exception.Message);
            }
            return reader2;
        }

        public static int ExecuteSql(string SQLString)
        {
            int num2;
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                OleDbCommand command = new OleDbCommand(SQLString, connection);
                try
                {
                    connection.Open();
                    num2 = command.ExecuteNonQuery();
                }
                catch (OleDbException exception)
                {
                    connection.Close();
                    throw new Exception(exception.Message);
                }
                finally
                {
                    if (command != null)
                    {
                        command.Dispose();
                    }
                }
            }
            return num2;
        }


        public static int ExecuteSql(string SQLString, params OleDbParameter[] cmdParms)
        {
            int num2;
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                OleDbCommand cmd = new OleDbCommand();
                try
                {
                    PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                    num2 = cmd.ExecuteNonQuery();
                    cmd.Parameters.Clear();
                    // return num;
                }
                catch (OleDbException exception)
                {
                    throw new Exception(exception.Message);
                }
                finally
                {
                    if (cmd != null)
                    {
                        cmd.Dispose();
                    }
                }
            }
            return num2;
        }


        public static void ExecuteSqlTran(ArrayList SQLStringList)
        {
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                connection.Open();
                OleDbCommand command = new OleDbCommand();
                command.Connection = connection;
                OleDbTransaction transaction = connection.BeginTransaction();
                command.Transaction = transaction;
                try
                {
                    for (int i = 0; i < SQLStringList.Count; i++)
                    {
                        string str = SQLStringList[i].ToString();
                        if (str.Trim().Length > 1)
                        {
                            command.CommandText = str;
                            command.ExecuteNonQuery();
                        }
                    }
                    transaction.Commit();
                }
                catch (OleDbException exception)
                {
                    transaction.Rollback();
                    throw new Exception(exception.Message);
                }
            }
        }

        public static void ExecuteSqlTran(Hashtable SQLStringList)
        {
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                connection.Open();
                using (OleDbTransaction transaction = connection.BeginTransaction())
                {
                    OleDbCommand cmd = new OleDbCommand();
                    try
                    {
                        foreach (DictionaryEntry entry in SQLStringList)
                        {
                            string cmdText = entry.Key.ToString();
                            OleDbParameter[] cmdParms = (OleDbParameter[])entry.Value;
                            PrepareCommand(cmd, connection, transaction, cmdText, cmdParms);
                            int num = cmd.ExecuteNonQuery();
                            cmd.Parameters.Clear();
                            transaction.Commit();
                        }
                    }
                    catch
                    {
                        transaction.Rollback();
                        throw;
                    }
                }
            }
        }

        public static bool Exists(string strSql)
        {
            int num;
            object single = GetSingle(strSql);
            if (object.Equals(single, null) || object.Equals(single, DBNull.Value))
            {
                num = 0;
            }
            else
            {
                num = int.Parse(single.ToString());
            }
            if (num == 0)
            {
                return false;
            }
            return true;
        }

        public static bool Exists(string strSql, params OleDbParameter[] cmdParms)
        {
            int num;
            object single = GetSingle(strSql, cmdParms);
            if (object.Equals(single, null) || object.Equals(single, DBNull.Value))
            {
                num = 0;
            }
            else
            {
                num = int.Parse(single.ToString());
            }
            if (num == 0)
            {
                return false;
            }
            return true;
        }


        public static int GetMaxID(string Num_FieldName, string TableName)
        {
            object single = GetSingle("select max(" + Num_FieldName + ")+1 from " + TableName);
            if (single == null)
            {
                return 1;
            }
            return int.Parse(single.ToString());
        }

        public static object GetSingle(string SQLString)
        {
            object objA;
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                OleDbCommand command = new OleDbCommand(SQLString, connection);
                try
                {
                    connection.Open();
                    objA = command.ExecuteScalar();
                    if (object.Equals(objA, null) || object.Equals(objA, DBNull.Value))
                    {
                        return null;
                    }
                    // return objA;
                }
                catch (OleDbException exception)
                {
                    connection.Close();
                    throw new Exception(exception.Message);
                }
                finally
                {
                    if (command != null)
                    {
                        command.Dispose();
                    }
                }
                connection.Close();
                connection.Dispose();
            }
            return objA;
        }

        public static object GetSingle(string SQLString, params OleDbParameter[] cmdParms)
        {
            object objA;
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                OleDbCommand cmd = new OleDbCommand();
                try
                {
                    PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                    objA = cmd.ExecuteScalar();
                    cmd.Parameters.Clear();
                    if (object.Equals(objA, null) || object.Equals(objA, DBNull.Value))
                    {
                        return null;
                    }
                    // return objA;
                }
                catch (OleDbException exception)
                {
                    throw new Exception(exception.Message);
                }
                finally
                {
                    if (cmd != null)
                    {
                        cmd.Dispose();
                    }
                }
                connection.Close();
                connection.Dispose();
            }
            
            return objA;
        }

        private static void PrepareCommand(OleDbCommand cmd, OleDbConnection conn, OleDbTransaction trans, string cmdText, OleDbParameter[] cmdParms)
        {
            if (conn.State != System.Data.ConnectionState.Open)
            {
                conn.Open();
            }
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            if (trans != null)
            {
                cmd.Transaction = trans;
            }
            cmd.CommandType = CommandType.Text;
            if (cmdParms != null)
            {
                foreach (OleDbParameter parameter in cmdParms)
                {
                    cmd.Parameters.Add(parameter);
                }
            }
        }

        public static DataSet Query(string SQLString)
        {
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                DataSet dataSet = new DataSet();
                try
                {
                    connection.Open();
                    new OleDbDataAdapter(SQLString, connection).Fill(dataSet, "ds");
                }
                catch (OleDbException exception)
                {
                    throw new Exception(exception.Message);
                }
                return dataSet;
            }
        }

        public static DataSet Query(string SQLString, params OleDbParameter[] cmdParms)
        {
            DataSet set2;
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                OleDbCommand cmd = new OleDbCommand();
                PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                using (OleDbDataAdapter adapter = new OleDbDataAdapter(cmd))
                {
                    DataSet dataSet = new DataSet();
                    try
                    {
                        adapter.Fill(dataSet, "ds");
                        cmd.Parameters.Clear();
                    }
                    catch (OleDbException exception)
                    {
                        throw new Exception(exception.Message);
                    }
                    set2 = dataSet;
                }
            }
            return set2;
        }

        public static string Get_SelectFieldName(int Top, params string[] SelectFieldName)
        {
            StringBuilder SelectFields = new StringBuilder();
            if (SelectFieldName.Length > 0)
            {
                foreach (string str in SelectFieldName)
                {
                    SelectFields.Append(str + ",");
                }
                SelectFields.Remove(SelectFields.Length - 1, 1);
            }
            else
            {
                SelectFields.Append("*");
            }
            if (Top > 0)
                SelectFields.Insert(0, "select top " + Top.ToString());
            else
                SelectFields.Insert(0, "select ");
            return SelectFields.ToString();
        }

        public static int DataInsert(string TableName, string[] FieldValues, params string[] FieldNames)
        {
            StringBuilder SelectFields = new StringBuilder();
            StringBuilder ValueFields = new StringBuilder();
            if (FieldNames.Length > 0)
            {
                foreach (string str in FieldNames)
                {
                    SelectFields.Append(str + ",");
                    ValueFields.Append("@" + str + ",");

                }
                SelectFields.Remove(SelectFields.Length - 1, 1);
                ValueFields.Remove(ValueFields.Length - 1, 1);
            }
            else
            {
                throw new Exception("Fields Error!");
            }
            string sql = string.Format("insert into {0}({1}) values({2})", TableName, SelectFields.ToString(), ValueFields.ToString());
            OleDbParameter[] cmdParms = new OleDbParameter[FieldNames.Length];
            for (int i = 0; i < FieldNames.Length; i++)
            {
                int FieldSize = 0;
                object FieldValue = FieldValues[i];
                System.Data.OleDb.OleDbType DbType = Get_dbFieldType(TableName, FieldNames[i], ref FieldSize, ref FieldValue);
                if (FieldSize == 0)
                    cmdParms[i] = new OleDbParameter("@" + FieldNames[i], DbType);
                else
                    cmdParms[i] = new OleDbParameter("@" + FieldNames[i], DbType, FieldSize);

                cmdParms[i].Value = FieldValue;
            }
            return ExecuteSql(sql, cmdParms);
        }

        public static int DataUpdate(string TableName, string IndexField, string IndexFieldValue, string[] UpdateFieldValue, params string[] UpdateFields)
        {
            StringBuilder SelectFields = new StringBuilder();
            if (UpdateFields.Length > 0)
            {
                foreach (string str in UpdateFields)
                {
                    SelectFields.Append(str + "=@" + str + ",");
                }
                SelectFields.Remove(SelectFields.Length - 1, 1);
            }
            else
            {
                throw new Exception("Fields Error!");
            }
            string sql = string.Format("update {0} set {1} where {2}='{3}'", TableName.ToString(), SelectFields.ToString(), IndexField, IndexFieldValue);
            OleDbParameter[] cmdParms = new OleDbParameter[UpdateFields.Length];
            for (int i = 0; i < UpdateFields.Length; i++)
            {
                int FieldSize = 0;
                object FieldValue = UpdateFieldValue[i];
                System.Data.OleDb.OleDbType DbType = Get_dbFieldType(TableName.ToString(), UpdateFields[i], ref FieldSize, ref FieldValue);
                if(FieldSize==0)
                   cmdParms[i] = new OleDbParameter("@" + UpdateFields[i], DbType);
                else
                    cmdParms[i] = new OleDbParameter("@" + UpdateFields[i], DbType,FieldSize);

                cmdParms[i].Value = FieldValue;
            }
            return ExecuteSql(sql, cmdParms);
        }

        private static System.Data.OleDb.OleDbType Get_dbFieldType(string TableName, string Field, ref int FieldSize, ref object FieldValue)
        {
            string sql = string.Format("select top 1 {0} from {1}", Field, TableName);
            System.Data.OleDb.OleDbDataReader dr = ExecuteReader(sql);
            System.Type FieldType= dr.GetFieldType(0);
            string FieldTypeStr=FieldType.ToString();
            System.Data.OleDb.OleDbType tmpType = System.Data.OleDb.OleDbType.VarChar;
            switch (FieldTypeStr)
            {
                case "System.String":
                    {
                        tmpType = System.Data.OleDb.OleDbType.VarChar;
                        FieldSize = FieldValue.ToString().Length;
                        FieldValue = FieldValue.ToString();
                        break;
                    }
                case "System.Decimal":
                    {
                        tmpType = System.Data.OleDb.OleDbType.Decimal;
                        FieldSize = 0;
                        FieldValue = Convert.ToDecimal(FieldValue.ToString());
                        break;
                    }
                case "System.DateTime":
                    {
                        tmpType = System.Data.OleDb.OleDbType.Date;
                        FieldSize = 0;
                        FieldValue = Convert.ToDateTime(FieldValue.ToString());
                        break;
                    }
                case "System.Double":
                    {
                        tmpType = System.Data.OleDb.OleDbType.Double;
                        FieldSize = 0;
                        FieldValue = Convert.ToDouble(FieldValue.ToString());
                        break;
                    }
                case "System.Int32":
                    {
                        tmpType = System.Data.OleDb.OleDbType.Integer;
                        FieldSize = 0;
                        FieldValue = Convert.ToInt32(FieldValue.ToString());
                        break;
                    }
                case "System.Boolean":
                    {
                        tmpType = System.Data.OleDb.OleDbType.Boolean;
                        FieldSize = 0;
                        FieldValue = Convert.ToBoolean(FieldValue);
                        break;
                    }
            }
            return tmpType;

        }

    }
}
