using DevExpress.CodeParser;
using DevExpress.Data.Helpers;
using DevExpress.Data.ODataLinq.Helpers;
using DevExpress.Internal.WinApi.Windows.UI.Notifications;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.Odbc;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using SystemX.Net.Platform.Common.Util;
using static SystemX.Net.Platform.Common.Util.LogMessage;

namespace DataBaseConnection.Control
{
    public class DatabaseConnControl
    {
        /*public static string MainCatalogName = "CPX";
        public static string ShortTermCatalogName = "CPX";
        public static string LongTermCatalogName = "CPXLog";*/

        public static string MainCatalogName = "CPXV2";
        public static string ShortTermCatalogName = "";
        public static List<string> LongTermCatalogName = new List<string> { "" } ;
        public static string SelectLongTermCatalogNameCon1 = string.Empty;
        public static string SelectLongTermCatalogNameCon2 = string.Empty;
        public static bool ScanLongTermLog = false;

        public const string Address = "192.168.0.43";
        public const int CatalogConnPort = 1433;

        public const string CatalogConnUID = "Alis";

        public const string CatalogConnPW = "Kefico!@34";

        private static SqlConnection connMain = null;

        private static SqlConnection connShortTerm1 = null;
        private static Dictionary<string, SqlConnection> connLongTerm1 = new Dictionary<string, SqlConnection>();

        private static SqlConnection connShortTerm2 = null;
        private static Dictionary<string, SqlConnection>  connLongTerm2 = new Dictionary<string, SqlConnection>();

        public static SqlConnection GetMainConn()
        {
            return connMain;
        }

        public static SqlConnection GetShortTermConn1()
        {
            return connShortTerm1;
        }

        public static Dictionary<string, SqlConnection> GetLongTermConn1()
        {
            return connLongTerm1;
        }

        public static SqlConnection GetShortTermConn2()
        {
            return connShortTerm2;
        }

        public static Dictionary<string, SqlConnection> GetLongTermConn2()
        {
            return connLongTerm2;
        }

        public DatabaseConnControl()
        {
            //conn = new SqlConnection($"Data Source=200.200.200.48,1433; Initial Catalog={CatalogName}; User ID=Alis; Password=kefico; MultipleActiveResultSets=True;");        
            //conn = new SqlConnection($"Data Source=DESKTOP-5UQ1Q22;Initial Catalog={CatalogName};Integrated Security=True;");     
            //conn = new SqlConnection($"Data Source = 125.130.37.164,1433; Initial Catalog = {CatalogName}; User ID = Alis; Password = kefico; MultipleActiveResultSets=True;");
            //"Data Source = {IP},{Port}; Initial Catalog = {CatalogName}; User ID = Alis; Password = kefico; MultipleActiveResultSets=True;";
            //"Data Source = localhost; Initial Catalog = {CatalogName}; Integrated Security = SSPI; MultipleActiveResultSets=True;";
        }

        public static void DisconnectDB()
        {
            if (connMain != null)
            {
                if (connMain.State == System.Data.ConnectionState.Open)
                    connMain.Close();
            }
            //
            if (connShortTerm1 != null)
            {
                if (connShortTerm1.State == System.Data.ConnectionState.Open)
                    connShortTerm1.Close();
            }
            //           
            if (connLongTerm1?.Count > 0)
            {
                foreach (var logTermConnection in connLongTerm1.Values)
                {
                    if (logTermConnection.State == System.Data.ConnectionState.Open)
                        logTermConnection.Close();
                }               
            }
            //
            if (connShortTerm2 != null)
            {
                if (connShortTerm2.State == System.Data.ConnectionState.Open)
                    connShortTerm2.Close();
            }
            //
            if (connLongTerm2?.Count > 0)
            {
                foreach (var logTermConnection in connLongTerm2.Values)
                {
                    if (logTermConnection.State == System.Data.ConnectionState.Open)
                        logTermConnection.Close();
                }
            }
        }

        public static void ConnectTestListDB()
        {
            try
            {
                connMain = new SqlConnection($"Data Source=localhost; Initial Catalog={MainCatalogName}; Integrated Security = SSPI; MultipleActiveResultSets=True;");
                connMain.Open();

                SqlCommand SQLCmd = new SqlCommand("spGetDBList", connMain);
                SQLCmd.CommandType = CommandType.StoredProcedure;
                DbDataReader dtReader = SQLCmd.ExecuteReader();

                DataTable dtResult = new DataTable();
                dtResult.Load(dtReader);
                List<string> list = dtResult?.AsEnumerable()?.Select(x=>x.ItemArray?.First()?.ToString())?.ToList();
                if(list?.Count > 0)
                {
                    //short term
                    var shortTermCatalogName = list.Find(x => x.ToLower().Contains("short"));
                    if(string.IsNullOrEmpty(shortTermCatalogName) ==false)
                    {
                        ShortTermCatalogName = shortTermCatalogName;
                    }

                    //long term
                    var longTermCatalogName = list.FindAll(x => x.ToLower().Contains("long"));
                    if(longTermCatalogName?.Count() > 0)
                    {
                        LongTermCatalogName?.Clear();
                        LongTermCatalogName.AddRange(longTermCatalogName);
                    }
                }

                dtReader.Close();
            }
            catch (SqlException sqlEx)
            {
                MessageOutput.ConsoleWrite($"TestList DB Connection Error: {sqlEx.Message}", ConsoleColor.Red, LogMessage.LogMessageLevel.FATAL);

                connMain = null;
            }
        }

        public static void ConnectDataDB1()
        {
            try
            {
                connShortTerm1 = new SqlConnection($"Data Source=localhost; Initial Catalog={ShortTermCatalogName}; Integrated Security = SSPI; MultipleActiveResultSets=True;"); // MultipleActiveResultSets=True;");
                connShortTerm1.Open();

                foreach(var catalog in LongTermCatalogName)
                {
                    connLongTerm1.Add(catalog, new SqlConnection($"Data Source=localhost; Initial Catalog={catalog}; Integrated Security = SSPI; MultipleActiveResultSets=True;")); // MultipleActiveResultSets=True;");

                    if (connLongTerm1.TryGetValue(catalog, out var connecction) == true)
                    {
                        connecction.Open();
                    }                    
                }
            }
            catch (SqlException sqlEx)
            {
                MessageOutput.ConsoleWrite($"Data DB Connection Error: {sqlEx.Message}", ConsoleColor.Red, LogMessage.LogMessageLevel.FATAL);

                connShortTerm1 = null;
                connLongTerm1 = null;
            }
        }

        public static void ConnectDataDB2()
        {
            try
            {
                connShortTerm2 = new SqlConnection($"Data Source=localhost; Initial Catalog={ShortTermCatalogName}; Integrated Security = SSPI; MultipleActiveResultSets=True;"); // MultipleActiveResultSets=True;");
                connShortTerm2.Open();

                foreach (var catalog in LongTermCatalogName)
                {
                    connLongTerm2.Add(catalog, new SqlConnection($"Data Source=localhost; Initial Catalog={catalog}; Integrated Security = SSPI; MultipleActiveResultSets=True;")); // MultipleActiveResultSets=True;");

                    if (connLongTerm2.TryGetValue(catalog, out var connecction) == true)
                    {
                        connecction.Open();
                    }
                }
            }
            catch (SqlException sqlEx)
            {
                MessageOutput.ConsoleWrite($"Data DB Connection Error: {sqlEx.Message}", ConsoleColor.Red, LogMessage.LogMessageLevel.FATAL);

                connShortTerm2 = null;
                connLongTerm2 = null;
            }
        }

        public static void ConnectTestListDB(string strGetConnIPAddress, int nGetConnPort = CatalogConnPort)
        {
            try
            {
                //conn = new SqlConnection("Data Source=200.200.200.48,1433; Initial Catalog=LSU_Trimming_4th_ALIS; User ID=Alis; Password=kefico; MultipleActiveResultSets=True;");          
                //Data Source = {IP},{Port}; Initial Catalog = {SCHEMA}; User ID = {ID}; Password = {PW}; MultipleActiveResultSets=True;
                //conn = new SqlConnection("Data Source=DESKTOP-5UQ1Q22;Initial Catalog=LSU_Trimming_4th_ALIS;Integrated Security=True;");     
                //conn = new SqlConnection("Data Source = 125.130.37.164,1433; Initial Catalog = LSU_Trimming_4th_ALIS; User ID = Alis; Password = kefico; MultipleActiveResultSets=True;");            
                //conn = new SqlConnection("Data Source = 127.0.0.1; Initial Catalog = Smart_Inhibitor_1th_ALIS; User ID = Alis; Password = kefico;"); //Integrated Security = SSPI;");

                SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();

                if (strGetConnIPAddress.Split(',').Length == 2)
                    builder.DataSource = strGetConnIPAddress;
                else
                    builder.DataSource = strGetConnIPAddress + "," + nGetConnPort.ToString();

                builder.UserID = "Alis";
                builder.Password = "Kefico!@34";
                builder.InitialCatalog = MainCatalogName;
                builder.MultipleActiveResultSets = true;

                connMain = new SqlConnection(builder.ConnectionString);
                connMain.Open();
                //
                if (strGetConnIPAddress.Split(',').Length == 2)
                    builder.DataSource = strGetConnIPAddress;
                else
                    builder.DataSource = strGetConnIPAddress + "," + nGetConnPort.ToString();

                SqlCommand SQLCmd = new SqlCommand("spGetDBList", connMain);
                SQLCmd.CommandType = CommandType.StoredProcedure;
                DbDataReader dtReader = SQLCmd.ExecuteReader();

                DataTable dtResult = new DataTable();
                dtResult.Load(dtReader);
                List<string> list = dtResult?.AsEnumerable()?.Select(x => x.ItemArray?.First()?.ToString())?.ToList();
                if (list?.Count > 0)
                {
                    //short term
                    var shortTermCatalogName = list.Find(x => x.ToLower().Contains("short") && x.ToLower().Contains("json"));
                    if (string.IsNullOrEmpty(shortTermCatalogName) == false)
                    {
                        ShortTermCatalogName = shortTermCatalogName;
                    }

                    //long term
                    var longTermCatalogName = list.FindAll(x => x.ToLower().Contains("long") && x.ToLower().Contains("json"));
                    if (longTermCatalogName?.Count() > 0)
                    {
                        LongTermCatalogName?.Clear();
                        LongTermCatalogName.AddRange(longTermCatalogName);
                    }
                }

                dtReader.Close();

            }
            catch (SqlException sqlEx)
            {
                MessageOutput.ConsoleWrite($"TestList DB Connection Error: {sqlEx.Message}", ConsoleColor.Red, LogMessage.LogMessageLevel.FATAL);

                connMain = null;
            }
        }

        public static void ConnectDataDB1(string strGetConnIPAddress, int nGetConnPort = CatalogConnPort, string CatalogName = "")
        {
            try
            {
                //conn = new SqlConnection("Data Source=200.200.200.48,1433; Initial Catalog=LSU_Trimming_4th_ALIS; User ID=Alis; Password=kefico; MultipleActiveResultSets=True;");          
                //Data Source = {IP},{Port}; Initial Catalog = {SCHEMA}; User ID = {ID}; Password = {PW}; MultipleActiveResultSets=True;
                //conn = new SqlConnection("Data Source=DESKTOP-5UQ1Q22;Initial Catalog=LSU_Trimming_4th_ALIS;Integrated Security=True;");     
                //conn = new SqlConnection("Data Source = 125.130.37.164,1433; Initial Catalog = LSU_Trimming_4th_ALIS; User ID = Alis; Password = kefico; MultipleActiveResultSets=True;");            
                //conn = new SqlConnection("Data Source = 127.0.0.1; Initial Catalog = Smart_Inhibitor_1th_ALIS; User ID = Alis; Password = kefico;"); //Integrated Security = SSPI;");

                SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();

                if (strGetConnIPAddress.Split(',').Length == 2)
                    builder.DataSource = strGetConnIPAddress;
                else
                    builder.DataSource = strGetConnIPAddress + "," + nGetConnPort.ToString();

                builder.UserID = "Alis";
                builder.Password = "Kefico!@34"; //"Kefico!@34";
                //builder.Password = "KEFICO!@34";
                builder.InitialCatalog = ShortTermCatalogName;

                //conn = new SqlConnection(builder.ConnectionString);
                connShortTerm1 = new SqlConnection(builder.ConnectionString);
                //conn = new SqlConnection("Data Source = " + strGetConnIPAddress.ToString() + ",1433; Initial Catalog = Smart_Inhibitor_1th_ALIS; User ID=Alis; Password=KEFICO!@34;"); // MultipleActiveResultSets=True;");
                connShortTerm1.Open();
                //
                builder = new SqlConnectionStringBuilder();

                if (strGetConnIPAddress.Split(',').Length == 2)
                    builder.DataSource = strGetConnIPAddress;
                else
                    builder.DataSource = strGetConnIPAddress + "," + nGetConnPort.ToString(); //9000 50001 50002

                builder.UserID = "Alis";
                builder.Password = "Kefico!@34";
                builder.InitialCatalog = CatalogName;
                builder.MultipleActiveResultSets = true;

                try
                {
                    var con = new SqlConnection(builder.ConnectionString);
                    con.Open();
                    connLongTerm1.Add(CatalogName, con);

                }
                catch(Exception ex)
                {
                    MessageOutput.ConsoleWrite($"Data DB Connection Error: {ex.Message}", ConsoleColor.Red, LogMessage.LogMessageLevel.FATAL);
                }
            }
            catch (SqlException sqlEx)
            {
                MessageOutput.ConsoleWrite($"Data DB Connection Error: {sqlEx.Message}", ConsoleColor.Red, LogMessage.LogMessageLevel.FATAL);

                connShortTerm1 = null;
                connLongTerm1 = null;
            }
        }

        public static void ConnectDataDB2(string strGetConnIPAddress, int nGetConnPort = CatalogConnPort, string CatalogName = "")
        {
            try
            {
                //conn = new SqlConnection("Data Source=200.200.200.48,1433; Initial Catalog=LSU_Trimming_4th_ALIS; User ID=Alis; Password=kefico; MultipleActiveResultSets=True;");          
                //Data Source = {IP},{Port}; Initial Catalog = {SCHEMA}; User ID = {ID}; Password = {PW}; MultipleActiveResultSets=True;
                //conn = new SqlConnection("Data Source=DESKTOP-5UQ1Q22;Initial Catalog=LSU_Trimming_4th_ALIS;Integrated Security=True;");     
                //conn = new SqlConnection("Data Source = 125.130.37.164,1433; Initial Catalog = LSU_Trimming_4th_ALIS; User ID = Alis; Password = kefico; MultipleActiveResultSets=True;");            
                //conn = new SqlConnection("Data Source = 127.0.0.1; Initial Catalog = Smart_Inhibitor_1th_ALIS; User ID = Alis; Password = kefico;"); //Integrated Security = SSPI;");

                SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();

                if (strGetConnIPAddress.Split(',').Length == 2)
                    builder.DataSource = strGetConnIPAddress;
                else
                    builder.DataSource = strGetConnIPAddress + "," + nGetConnPort.ToString();

                builder.UserID = "Alis";
                builder.Password = "Kefico!@34"; //"Kefico!@34";
                //builder.Password = "KEFICO!@34";
                builder.InitialCatalog = ShortTermCatalogName;

                //conn = new SqlConnection(builder.ConnectionString);
                connShortTerm2 = new SqlConnection(builder.ConnectionString);
                //conn = new SqlConnection("Data Source = " + strGetConnIPAddress.ToString() + ",1433; Initial Catalog = Smart_Inhibitor_1th_ALIS; User ID=Alis; Password=KEFICO!@34;"); // MultipleActiveResultSets=True;");
                connShortTerm2.Open();
                //
                builder = new SqlConnectionStringBuilder();

                if (strGetConnIPAddress.Split(',').Length == 2)
                    builder.DataSource = strGetConnIPAddress;
                else
                    builder.DataSource = strGetConnIPAddress + "," + nGetConnPort.ToString(); //9000 50001 50002

                builder.UserID = "Alis";
                builder.Password = "Kefico!@34";
                builder.InitialCatalog = CatalogName;
                builder.MultipleActiveResultSets = true;

                try
                {
                    var con = new SqlConnection(builder.ConnectionString);
                    con.Open();
                    connLongTerm2.Add(CatalogName, con);

                }
                catch (Exception ex)
                {
                    MessageOutput.ConsoleWrite($"Data DB Connection Error: {ex.Message}", ConsoleColor.Red, LogMessage.LogMessageLevel.FATAL);
                }
            }
            catch (SqlException sqlEx)
            {
                MessageOutput.ConsoleWrite($"Data DB Connection Error: {sqlEx.Message}", ConsoleColor.Red, LogMessage.LogMessageLevel.FATAL);

                connShortTerm2 = null;
                connLongTerm2 = null;
            }
        }
    }
}