using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Diagnostics.Eventing.Reader;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Markup;
using Windows.Phone.PersonalInformation;

namespace ZKuP
{
    public static class SQL
    {
        private static string p = "fNZG8bO+b8lbajxNUCPCIRNBap4/T5N5Qoa0Rec3P9b2EiwC5eNIwfEMjR5Fvc/W";
        private static string s = "KYgjkRVn0edFDca2GbZq/A==";
        private static string uSSL = "miSRZrFLxAAWlzRLx9B6Ww==";
        private static string d = "xWb4X9gPEzwe76zqpysF3w==";
#if DEBUG
        private static string u = "F/u2njMf6aE4krZGTjzgZw==";
        private static string dTest = "e+tv3ZaP+cewOJgE7jNNlA==";
#endif
        //static MySqlConnection conn = new MySqlConnection(GetConnstr());
        //private static MySqlConnection _conn;
        //public static MySqlConnection conn
        //{
        //    get 
        //    {
        //        _conn = new MySqlConnection(GetConnstr());
        //        return _conn; 
        //    }
        //    set { _conn = value; }
        //}
        public static bool isOnline = false;

        static MySqlDataAdapter adp = new MySqlDataAdapter();

        public static bool CheckOnline()
        {
            System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping();
            //change the following ip variable into the ip adress you are looking for
            System.Net.IPAddress address = System.Net.IPAddress.Parse(GetIP());
            System.Net.NetworkInformation.PingReply pong = ping.Send(address);
            if (pong.Status == System.Net.NetworkInformation.IPStatus.Success)
            {
                return true;
            }
            else
            {
                pong = ping.Send(address);

                if (pong.Status == System.Net.NetworkInformation.IPStatus.Success)
                {
                    return true;
                }
                else
                {
                    isOnline = false;
                    return false;
                }
            }
        }

        public static bool CheckDeviceConnection()
        {
            System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping();
            //change the following ip variable into the ip adress you are looking for
            System.Net.IPAddress address = System.Net.IPAddress.Parse(GetIP());
            System.Net.NetworkInformation.PingReply pong = ping.Send(address);
            if (pong.Status == System.Net.NetworkInformation.IPStatus.Success)
            {
                return true;
            }
            else
            {
                pong = ping.Send(address);

                if (pong.Status == System.Net.NetworkInformation.IPStatus.Success)
                {
                    return true;
                }
                else
                {
                    isOnline = false;
                    System.Windows.MessageBox.Show($"Server ist nicht erreichbar\nNetzwerkverbindung überprüfen", "Fehler", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                    System.Windows.Application.Current.Shutdown();
                    return false;
                }
            }
        }

        static string ip = "";
        private static string GetIP()
        {
            if (string.IsNullOrWhiteSpace(ip))
            {
                ip = Crypto.Decrypt(Crypto.GetHashKey("866D137B10C95A4E8D5091B0CC0EFB8F"), s);
                return ip;
            }
            else return ip;
        }

        internal static string GetConnstr(bool withTimeout = false)
        {
#if !DEBUG
//Mit SSL
            return $"Server={GetIP()};" +
                $"Uid={Crypto.Decrypt(Crypto.GetHashKey("8734FCD0D69756D3AE7154E69F8042CA"), uSSL)};" +
                $"Pwd={Crypto.Decrypt(Crypto.GetHashKey("71A209CC81FDB2F458C4EC8DF7090154"), p)};" +
                $"database={Crypto.Decrypt(Crypto.GetHashKey("8EB0CC56E502BFC5C19F6A0A0A53D543"), d)}" +
                $";SslMode=Required;{(withTimeout ? "Connection Timeout = 10" : "")}";

//Ohne SSL
            //return $"Server={GetIP()};" +
            //    $"Uid={Crypto.Decrypt(Crypto.GetHashKey("990C535389C3A18FFD44951DAA291161"), u)};" +
            //    $"Pwd={Crypto.Decrypt(Crypto.GetHashKey("71A209CC81FDB2F458C4EC8DF7090154"), p)};" +
            //    $"database={Crypto.Decrypt(Crypto.GetHashKey("8EB0CC56E502BFC5C19F6A0A0A53D543"), d)}" +
            //    $";{(withTimeout ? "Connection Timeout = 10" : "")}";

#elif DEBUG
            ////Ohne SSL
            //return $"Server={GetIP()};" +
            //    $"Uid={Crypto.Decrypt(Crypto.GetHashKey("990C535389C3A18FFD44951DAA291161"), u)};" +
            //    $"Pwd={Crypto.Decrypt(Crypto.GetHashKey("71A209CC81FDB2F458C4EC8DF7090154"), p)};" +
            //    $"database={Crypto.Decrypt(Crypto.GetHashKey("B79DE37BC846D9B1054EE837AAA45D83"), dTest)}" +
            //    $";SslMode=none;{(withTimeout ? "Connection Timeout = 10" : "")}";


            //Mit SSL
            return $"Server={GetIP()};" +
                $"Uid={Crypto.Decrypt(Crypto.GetHashKey("8734FCD0D69756D3AE7154E69F8042CA"), uSSL)};" +
                $"Pwd={Crypto.Decrypt(Crypto.GetHashKey("71A209CC81FDB2F458C4EC8DF7090154"), p)};" +
                $"database={Crypto.Decrypt(Crypto.GetHashKey("B79DE37BC846D9B1054EE837AAA45D83"), dTest)}" +
                $";SslMode=Required;{(withTimeout ? "Connection Timeout = 10" : "")}";

#endif
        }
        public static MySqlDataAdapter GetAdapter()
        {
            return adp;
        }

        public static MySqlConnection GetConnection()
        {            
            //return conn;
            return new MySqlConnection(GetConnstr());
        }

        internal static bool IsSecureConnection()
        {
            //#if DEBUG
            using (var conn = GetConnection())
            {
                conn.Open();

                var cmd = new MySqlCommand("SHOW STATUS LIKE 'Ssl_cipher'", conn);
                using (var reader = cmd.ExecuteReader())
                {
                    string varName = "";
                    string varValue = "";

                    while (reader.Read())
                    {
                        varName = reader.GetString(0);  // Variable_name
                        varValue = reader.GetString(1); // Value
                        Console.WriteLine($"{varName}: {varValue}");
                    }


                    conn.Close();

                    if (varValue == "ECDHE-RSA-AES256-GCM-SHA384")
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
            //#endif
        }

        public static bool TestConnection()
        {
            if (!CheckDeviceConnection()) return false;

            var conn = GetConnection();

            using (conn)
            {
                try
                {
                    conn.Open();
                    conn.Close();

                    isOnline = true;
                    return true;
                }
                catch (Exception ex)
                {
                    conn.Close();
                    Log.WriteLog(ex.ToString());

                    isOnline = false;
                    System.Windows.MessageBox.Show($"Verbindung zum Server konnte nicht hergestellt werden\n\nInterne Meldung: {ex.Message}", "Fehler", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                    return false;
                }
            }
        }




        public static async Task<int> CreateAndWriteSQL(string strSQL, List<MySqlParameter> parameters)
        {
            var conn = GetConnection();
            MySqlCommand cmd = new MySqlCommand(strSQL, conn);

            foreach (MySqlParameter parameter in parameters)
                cmd.Parameters.Add(parameter);

            return await SQL.WriteSQL(cmd);
        }

        public static async Task CreateAndWriteSQL(MySqlCommand cmd)
        {
            //MySqlCommand cmd = new MySqlCommand(strSQL, conn);

            //foreach (MySqlParameter parameter in parameters)
            //    cmd.Parameters.Add(parameter);

            await SQL.WriteSQL(cmd);
        }

        public static async void CreateAndWriteSQL(string strSQL, Dictionary<string, object> parameters)
        {
            var conn = GetConnection();
            MySqlCommand cmd = new MySqlCommand(strSQL, conn);

            foreach (KeyValuePair<string, object> parameter in parameters)
                cmd.Parameters.Add(new MySqlParameter(parameter.Key, parameter.Value));

            await SQL.WriteSQL(cmd);
        }

        public static async Task CreateAndWriteSQLwithSignature(MySqlCommand cmd, byte[] signature)
        {
            //MySqlCommand cmd = new MySqlCommand(strSQL, conn);

            //foreach (MySqlParameter parameter in parameters)
            //    cmd.Parameters.Add(parameter);

            if (signature != null && signature.Length > 0)
                cmd.Parameters.Add("@signature", MySqlDbType.LongBlob).Value = signature;
            else cmd.Parameters.Add("@signature", MySqlDbType.LongBlob).Value = new byte[1];

                await SQL.WriteSQL(cmd);
        }



        public static MySqlCommand CreateAndReturnSQLCommand(string strSQL, List<MySqlParameter> parameters)
        {
            var conn = GetConnection();
            MySqlCommand cmd = new MySqlCommand(strSQL, conn);

            foreach (MySqlParameter parameter in parameters)
                cmd.Parameters.Add(parameter);

            return cmd;
        }

















        public static async Task<DataTable> WriteSQL(string SQLQuery, DataTable list)
        {
            var filter = list.DefaultView.RowFilter;

            var conn = GetConnection();
            try
            {
                var table = SQLQuery.Substring(SQLQuery.IndexOf($"{MainWindow.table}.") + MainWindow.table.Length + 1);
                table = table.Substring(0, table.IndexOf(' '));

                using (conn)
                {
                    using (adp)
                    {
                        conn.Close();

                        conn.Open();
                        adp.UpdateCommand = new MySqlCommand(SQLQuery, conn);

                        adp.Update(list);

                        list.AcceptChanges();
                    }


                    if (table.ToLower() == "firmen" || table.ToLower() == "besucher" || table.ToLower() == "family")
                    {
                        MySqlCommand updateCmd = new MySqlCommand($"UPDATE {MainWindow.table}.changes SET `timestamp` = '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}' WHERE `table` = '{table}'", conn);
                        using (updateCmd)
                        {
                            updateCmd.ExecuteNonQuery();
                        }
                    }


                    conn.Close();
                }

                list.DefaultView.RowFilter = filter;
            }
            catch (Exception ex)
            {
                conn.Close();
                Log.WriteLog(ex.ToString());
                return list;
            }

            return list;
        }

        public static async Task WriteSQL(string SQLQuery)
        {
            var conn = GetConnection();

            try
            {
                var table = SQLQuery.Substring(SQLQuery.IndexOf($"{MainWindow.table}.") + MainWindow.table.Length + 1);
                table = table.Substring(0, table.IndexOf(' '));

                using (conn)
                {
                    conn.Close();
                    conn.Open();

                    MySqlCommand cmd = new MySqlCommand(SQLQuery, conn);
                    using (cmd)
                    {
                        cmd.ExecuteNonQuery();
                    }

                    if (table.ToLower() == "firmen" || table.ToLower() == "besucher" || table.ToLower() == "family")
                    {
                        MySqlCommand updateCmd = new MySqlCommand($"UPDATE {MainWindow.table}.changes SET `timestamp` = '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}' WHERE `table` = '{table}'", conn);
                        using (updateCmd)
                        {
                            updateCmd.ExecuteNonQuery();
                        }
                    }

                    conn.Close();
                }
            }
            catch (Exception ex)
            {
                conn.Close();
                Log.WriteLog(ex.ToString());
            }
        }

        public static async Task<int> WriteSQLwithReturn(string SQLQuery)
        {
            var conn = GetConnection();
            var result = 0;

            try
            {
                var table = SQLQuery.Substring(SQLQuery.IndexOf($"{MainWindow.table}.") + MainWindow.table.Length + 1);
                table = table.Substring(0, table.IndexOf(' '));

                using (conn)
                {
                    conn.Close();
                    conn.Open();

                    MySqlCommand cmd = new MySqlCommand(SQLQuery, conn);
                    using (cmd)
                    {
                        result = cmd.ExecuteNonQuery();
                    }

                    if (table.ToLower() == "firmen" || table.ToLower() == "besucher" || table.ToLower() == "family")
                    {
                        MySqlCommand updateCmd = new MySqlCommand($"UPDATE {MainWindow.table}.changes SET `timestamp` = '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}' WHERE `table` = '{table}'", conn);
                        using (updateCmd)
                        {
                            updateCmd.ExecuteNonQuery();
                        }
                    }

                    conn.Close();
                }

                return result;
            }
            catch (Exception ex)
            {
                conn.Close();
                Log.WriteLog(ex.ToString());
                return result;
            }
        }


        public static async Task WriteSQL(string SQLQuery, byte[] data)
        {
            var conn = GetConnection();

            try
            {
                using (conn)
                {
                    conn.Close();
                    conn.Open();

                    MySqlCommand cmd = new MySqlCommand(SQLQuery, conn);
                    using (cmd)
                    {
                        cmd.Parameters.Add("@signature", MySqlDbType.LongBlob).Value = data;
                        cmd.ExecuteNonQuery();
                        conn.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                conn.Close();
                Log.WriteLog(ex.ToString());
            }
        }
        public static async Task<int> WriteSQL(MySqlCommand mySqlCommand)
        {
            var conn = GetConnection();

            try
            {
                var table = mySqlCommand.CommandText.Substring(mySqlCommand.CommandText.IndexOf($"{MainWindow.table}.") + MainWindow.table.Length + 1);
                table = table.Substring(0, table.IndexOf(' '));

                using (conn)
                {
                    conn.Close();
                    conn.Open();

                    mySqlCommand.Connection = conn;
                    var cmd = mySqlCommand;
                    using (cmd)
                    {
                        cmd.ExecuteNonQuery();
                    }


                    if (table.ToLower() == "firmen" || table.ToLower() == "besucher" || table.ToLower() == "family")
                    {
                        MySqlCommand updateCmd = new MySqlCommand($"UPDATE {MainWindow.table}.changes SET `timestamp` = '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}' WHERE `table` = '{table}'", conn);
                        using (updateCmd)
                        {
                            updateCmd.ExecuteNonQuery();
                        }
                    }

                    MySqlCommand Cmd = new MySqlCommand($"SELECT LAST_INSERT_ID()", conn);
                    int queryResult = 0;
                    using (Cmd)
                    {
                        int.TryParse(Cmd.ExecuteScalar().ToString(), out queryResult);
                    }


                    conn.Close();

                    return queryResult;
                }
            }
#pragma warning disable CS0168 // Variable ist deklariert, wird jedoch niemals verwendet
            catch (Exception ex)
#pragma warning restore CS0168 // Variable ist deklariert, wird jedoch niemals verwendet
            {
#if DEBUG
                conn.Close();
                throw;
#else
                conn.Close();
                Log.WriteLog(ex.ToString());
                return -1;
#endif
            }
        }



        public static async Task<DataTable> ReadSQL(string SQLCommand, DataTable list)
        {
            var conn = GetConnection();

            var filter = list.DefaultView.RowFilter;
            try
            {
                using (conn)
                {
                    using (adp)
                    {
                        conn.Close();

                        conn.Open();
                        adp.SelectCommand = new MySqlCommand(SQLCommand, conn);

                        list.Clear();
                        adp.Fill(list);
                        conn.Close();
                    }
                }

                list.DefaultView.RowFilter = filter;

            }
            catch (Exception ex)
            {
                conn.Close();
                Log.WriteLog(ex.ToString());
                return list;
            }

            return list;
        }

        public static async Task<DataTable> ReadSQL(string SQLCommand)
        {
            var conn = GetConnection();

            DataTable list = new DataTable();

            try
            {
                using (conn)
                {
                    using (adp)
                    {
                        conn.Close();

                        conn.Open();
                        adp.SelectCommand = new MySqlCommand(SQLCommand, conn);

                        list.Clear();
                        adp.Fill(list);
                        conn.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                conn.Close();
                Log.WriteLog(ex.ToString());
                return list;
            }

            return list;
        }


        public static string ReadSingleValue(string SQLCommand)
        {
            var conn = GetConnection();

            MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(SQLCommand, conn);
            object queryResult;

            using (conn)
            {
                using (cmd)
                {
                    conn.Close();

                    conn.Open();
                    queryResult = cmd.ExecuteScalar();//Return an object so first check for null
                }

                conn.Close();
            }

            if (queryResult != null)
                return queryResult.ToString();
            else
                return "";
        }

        public async static Task<string> ReadSingleValueAsync(string SQLCommand)
        {
            var conn = GetConnection();

            object queryResult;
            using (conn)
            {
                conn.Close();
                MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(SQLCommand, conn);

                using (cmd)
                {
                    conn.Open();
                    queryResult = await cmd.ExecuteScalarAsync();//Return an object so first check for null

                }

                conn.Close();
            }


            if (queryResult != null)
                return queryResult.ToString();
            else
                return "";
        }

        public static System.Drawing.Bitmap ReadSingleByteArr(string SQLCommand)
        {
            var conn = GetConnection();

            MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(SQLCommand, conn);
            //UInt32 FileSize;
            //byte[] rawData;
            System.Drawing.Bitmap image = null;

            using (conn)
            {
                using (cmd)
                {
                    conn.Close();

                    conn.Open();

                    MySql.Data.MySqlClient.MySqlDataReader myData = cmd.ExecuteReader();
                    using (myData)
                    {
                        while (myData.Read())
                        {
                            if (myData[0] == DBNull.Value)
                                return null;

                            byte[] data = (byte[])myData[0]; // 0 is okay if you only selecting one column
                                                             //And use:
                                                             //using (System.IO.MemoryStream ms = new System.IO.MemoryStream(data))
                                                             //{
                            System.IO.MemoryStream ms = new System.IO.MemoryStream(data);
                            image = new System.Drawing.Bitmap(ms);
                            //}
                        }
                    }

                    conn.Close();
                }              
            }

            //if (rawData != null)
            //    return (byte[])rawData;
            //else
                return image;
        }

        public static async Task<List<string>> ReadListString(string SQLCommand, int ColumnID = 0)
        {
            var conn = GetConnection();

            MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(SQLCommand, conn);
            List<string> queryResult = new List<string>();

            using (conn)
            {
                conn.Close();

                conn.Open();

                using (MySqlDataReader reader = cmd.ExecuteReader())
                {
                    using (cmd)
                    {
                        while (reader.Read())
                        {
                            if (!reader.IsDBNull(ColumnID))
                                queryResult.Add(reader.GetValue(ColumnID).ToString());
                            else
                                queryResult.Add("");
                        }
                    }
                }

                conn.Close();
            }

            return queryResult;
        }

        /// <summary>
        /// Read two Columns, separated by ';'
        /// </summary>
        /// <param name="SQLCommand"></param>
        /// <param name="ColumnID"></param>
        /// <returns></returns>
        public static async Task<List<string>> ReadDateTimeAndStringList(string SQLCommand, int ColumnID = 0)
        {
            var conn = GetConnection();

            MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(SQLCommand, conn);
            List<string> queryResult = new List<string>();

            using (conn)
            {
                conn.Close();

                conn.Open();

                using (MySqlDataReader reader = cmd.ExecuteReader())
                {
                    using (cmd)
                    {
                        while (reader.Read())
                        {
                            queryResult.Add(reader.GetDateTime(ColumnID).ToString("yyyy-MM-dd HH:mm:ss") + ";" + reader.GetValue(ColumnID + 1).ToString());
                        }
                    }
                }

                conn.Close();
            }

            return queryResult;
        }

        /// <summary>
        /// Read two Columns, separated by ';' or choose Seperator
        /// </summary>
        /// <param name="SQLCommand"></param>
        /// <param name="Seperator"></param>
        /// <param name="ColumnID"></param>
        /// <returns></returns>
        public static async Task<List<string>> ReadListStringTwoColumns(string SQLCommand, string Seperator = ";", int ColumnID = 0)
        {
            var conn = GetConnection();

            MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(SQLCommand, conn);
            List<string> queryResult = new List<string>();

            using (conn)
            {
                conn.Close();

                conn.Open();

                using (MySqlDataReader reader = cmd.ExecuteReader())
                {
                    using (cmd)
                    {
                        while (reader.Read())
                        {
                            if (!reader.IsDBNull(ColumnID) && !reader.IsDBNull(ColumnID  + 1))
                                queryResult.Add(reader.GetValue(ColumnID).ToString() + $"{Seperator}" + reader.GetValue(ColumnID + 1).ToString());  
                            else
                                queryResult.Add("");
                        }
                    }
                }

                conn.Close();
            }

            return queryResult;
        }


        /// <summary>
        /// Read two Columns, separated by ';' or choose Seperator
        /// </summary>
        /// <param name="SQLCommand"></param>
        /// <param name="Seperator"></param>
        /// <param name="ColumnID"></param>
        /// <returns></returns>
        public static async Task<List<string>> ReadListStringMultipleColumns(string SQLCommand, int ColumnCount = 3, string SeperatorOne = ";", string SeperatorTwo = ";", string SeperatorThree = ";", string SeperatorFour = ";", int ColumnOne = 0, int ColumnTwo = 1, int ColumnThree = 2, int ColumnFour = 3, int ColumnFive = 4, string SeperatorFive = ";", int ColumnSix = 5)
        {
            var conn = GetConnection();

            MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(SQLCommand, conn);
            List<string> queryResult = new List<string>();

            using (conn)
            {
                conn.Close();

                conn.Open();

                using (MySqlDataReader reader = cmd.ExecuteReader())
                {
                    using (cmd)
                    {
                        while (reader.Read())
                        {
                            switch(ColumnCount)
                            {
                                case 1:
                                    queryResult.Add(reader.GetValue(ColumnOne).ToString());
                                    break;
                                case 2:
                                    queryResult.Add(reader.GetValue(ColumnOne).ToString() + $"{SeperatorOne}" + reader.GetValue(ColumnTwo).ToString());
                                    break;
                                case 3:
                                    queryResult.Add(reader.GetValue(ColumnOne).ToString() + $"{SeperatorOne}" + reader.GetValue(ColumnTwo).ToString() + $"{SeperatorTwo}" + reader.GetValue(ColumnThree).ToString());
                                    break;
                                case 4:
                                    queryResult.Add(reader.GetValue(ColumnOne).ToString() + $"{SeperatorOne}" + reader.GetValue(ColumnTwo).ToString() + $"{SeperatorTwo}" + reader.GetValue(ColumnThree).ToString() + $"{SeperatorThree}" + reader.GetValue(ColumnFour).ToString());
                                    break;
                                case 5:
                                    queryResult.Add(reader.GetValue(ColumnOne).ToString() + $"{SeperatorOne}" + reader.GetValue(ColumnTwo).ToString() + $"{SeperatorTwo}" + reader.GetValue(ColumnThree).ToString() + $"{SeperatorThree}" + reader.GetValue(ColumnFour).ToString() + $"{SeperatorFour}" + reader.GetValue(ColumnFive).ToString());
                                    break;
                                case 6:
                                    queryResult.Add(reader.GetValue(ColumnOne).ToString() + $"{SeperatorOne}" + reader.GetValue(ColumnTwo).ToString() + $"{SeperatorTwo}" + reader.GetValue(ColumnThree).ToString() + $"{SeperatorThree}" + reader.GetValue(ColumnFour).ToString() + $"{SeperatorFour}" + reader.GetValue(ColumnFive).ToString() + $"{SeperatorFive}" + reader.GetValue(ColumnSix).ToString());
                                    break;
                                default:
                                    queryResult.Add(reader.GetValue(ColumnOne).ToString());
                                    break;
                            }
                        }
                    }
                }

                conn.Close();
            }

            return queryResult;
        }



        public static async Task<Dictionary<int, string>> ReadDictionary(string SQLCommand, int FirstColumn, int SecondColumn)
        {
            var conn = GetConnection();

            MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(SQLCommand, conn);
            Dictionary<int, string> queryResult = new Dictionary<int, string>();

            using (conn)
            {
                conn.Close();

                conn.Open();

                using (MySqlDataReader reader = cmd.ExecuteReader())
                {
                    using (cmd)
                    {
                        while (reader.Read())
                        {
                            if (FirstColumn == 0 && SecondColumn == 0)
                            {
                                if (!queryResult.ContainsKey(0))
                                    queryResult.Add(0, reader.GetValue(SecondColumn).ToString());
                            }
                            else
                            {
                                var x = reader.GetInt32(FirstColumn);

                                if (!queryResult.ContainsKey(x))
                                    queryResult.Add(x, reader.GetValue(SecondColumn).ToString());
                            }
                                
                        }
                    }
                }

                conn.Close();
            }

            return queryResult;
        }

        public static async Task<Dictionary<string, string>> ReadDictionary2(string SQLCommand, int FirstColumn, int SecondColumn)
        {
            var conn = GetConnection();

            try
            {
                MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(SQLCommand, conn);
                Dictionary<string, string> queryResult = new Dictionary<string, string>();

                using (conn)
                {
                    conn.Close();

                    conn.Open();

                    using (MySqlDataReader reader = cmd.ExecuteReader())
                    {
                        using (cmd)
                        {
                            var firstVal = "";
                            var secondVal = "";

                            while (reader.Read())
                            {
                                if (reader.IsDBNull(FirstColumn))
                                    firstVal = "";
                                else firstVal = reader.GetValue(FirstColumn).ToString();

                                if (reader.IsDBNull(SecondColumn))
                                    secondVal = "";
                                else secondVal = reader.GetValue(SecondColumn).ToString();

                                if (!queryResult.ContainsKey(firstVal))
                                    queryResult.Add(firstVal, secondVal);


                                //if (!reader.IsDBNull(FirstColumn) && !reader.IsDBNull(SecondColumn))
                                //    if (!queryResult.ContainsKey(reader.GetValue(FirstColumn).ToString()))
                                //        queryResult.Add(reader.GetValue(FirstColumn).ToString(), reader.GetValue(SecondColumn).ToString());
                                //    else if (reader.IsDBNull(FirstColumn) && !reader.IsDBNull(SecondColumn))
                                //        continue;// queryResult.Add("", reader.GetString(SecondColumn));
                                //    else if (!reader.IsDBNull(FirstColumn) && reader.IsDBNull(SecondColumn))
                                //        if (!queryResult.ContainsKey(reader.GetValue(FirstColumn).ToString()))
                                //            queryResult.Add(reader.GetValue(FirstColumn).ToString(), "");

                            }
                        }
                    }

                    conn.Close();
                }
                return queryResult;

            }
            catch (Exception)
            {
                return new Dictionary<string, string>();
            }
        }


        public static async Task<bool> RowExists(string Table, string Column, string Value, bool isLike = false, string additionalWHERE = "")
        {
            var conn = GetConnection();

            MySqlCommand cmd;

            if (!isLike)
            {
                cmd = new MySql.Data.MySqlClient.MySqlCommand($"SELECT 1 FROM {Table} WHERE {Column} = @pValue{additionalWHERE} LIMIT 1", conn);
                cmd.Parameters.Add(new MySqlParameter("@pValue", Value));
            }
            else
            {
                cmd = new MySql.Data.MySqlClient.MySqlCommand($"SELECT 1 FROM {Table} WHERE {Column} LIKE @pValue{additionalWHERE} LIMIT 1", conn);
                cmd.Parameters.Add(new MySqlParameter("@pValue", $"%{Value}%"));
            }



            conn.Open();
            var result = cmd.ExecuteScalar();
            conn.Close();
            return result != null;


            //object queryResult;
            //var res = 0;

            //using (conn)
            //{
            //    using (cmd)
            //    {
            //        conn.Close();

            //        conn.Open();
            //        queryResult = cmd.ExecuteScalar();//Return an object so first check for null
            //    }
            //    conn.Close();
            //}

            //if (queryResult != null)
            //   res = Convert.ToInt16(queryResult);

            //if (res == 1)
            //    return true;
            //else if (res == 0)
            //    return false;
            //else return false;
        }





        public static string MySQLCommandToString(MySqlCommand mySqlCommand)
        {
            string cmdText = mySqlCommand.CommandText;

            foreach (MySqlParameter p in mySqlCommand.Parameters)
            {
                var repl = p.Value != null ? p.Value.ToString() : "";
                cmdText = cmdText.Replace($"@{p.ParameterName},", $"'{repl}',");
                cmdText = cmdText.Replace($"@{p.ParameterName} ", $"'{repl}' ");

                if (cmdText.EndsWith($"@{p.ParameterName}"))
                    cmdText = cmdText.Replace($"@{p.ParameterName}", $"'{repl}'");
            }

            return cmdText;
        }


        //public static async Task<DataTable> ReadAllData(DataTable list)
        //{
        //    var filter = list.DefaultView.RowFilter;

        //    using (conn)
        //    {
        //        if (conn.State == ConnectionState.Open) conn.Close();

        //        conn.Open();
        //        adp.SelectCommand = new MySqlCommand("select PersNr,Name,Vorname,Abteilung,o.Datum,Beginn,Gehen,Tagescode,Arbeitsmuster,Zuweisung,Bemerkung,Telefon,AnzahlLizenzen,ZugNameB from pep_tool.mitarbeiter_static p left join pep_tool.mitarbeiter_change o ON o.mitarbeiter_static_PersNr = p.PersNr ORDER BY Name", conn);
        //        list.Clear();
        //        adp.Fill(list);
        //        conn.Close();
        //    }

        //    list.DefaultView.RowFilter = filter;
        //    return list;
        //}

        //public static async Task<DataTable> ReadAllData(string filter = "")
        //{
        //    try
        //    {
        //        DataTable list = new DataTable("UserList");

        //        using (conn)
        //        {
        //            if (conn.State == ConnectionState.Open) conn.Close();

        //            conn.Open();
        //            adp.SelectCommand = new MySqlCommand("select PersNr,Name,Vorname,Abteilung,o.Datum,Beginn,Gehen,Tagescode,Arbeitsmuster,Zuweisung,Bemerkung,Telefon,AnzahlLizenzen,ZugNameB from pep_tool.mitarbeiter_static p left join pep_tool.mitarbeiter_change o ON o.mitarbeiter_static_PersNr = p.PersNr ORDER BY Name", conn);
        //            list.Columns.Clear();
        //            adp.Fill(list);
        //            conn.Close();
        //        }

        //        list.DefaultView.RowFilter = filter;
        //        return list;
        //    }
        //    catch (Exception ex)
        //    {
        //        System.Diagnostics.Debug.WriteLine(ex);
        //        return await ReadAllData();
        //    }
        //}
    }
}
