using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using static UWS.BusinessLayer;

namespace UWS
{
    class DataAccessObject
    {
        //********* URLs with IP Address (Local):

        //string POST_END_POINT_URL_LOCAL = "http://192.168.90.223:8081/uind/rest/uic/loading-vehicle-weight-info/save-details";
        //string GET_END_POINT_URL_LOCAL = "http://192.168.90.223:8081/uind/rest/uic/loading-vehicle-weight-info/get-loading-vehicle-weight-and-request-info?req-code=";
        //string urlGetVehicle = $"http://192.168.90.223:8081/uind/rest/uic/loading-vehicle-weight-info/get-loading-vehicle-weight-and-request-info-vehicle-no?vehicle-no=";
        //string urlDc = "http://192.168.90.223:8081/uind/rest/uic/dispatch-challan-weight-info/save-details";
        //string urlTrolley = "http://192.168.90.223:8081/uind/rest/uic/dispatch-challan-weight-info/get-trolleys";

        //************ URLs without IP Address (Production):

        string POST_END_POINT_URL = "https://portal.utopiaindustries.pk/uind/rest/uic/loading-vehicle-weight-info/save-details";
        string GET_END_POINT_URL = "https://portal.utopiaindustries.pk/uind/rest/uic/loading-vehicle-weight-info/get-loading-vehicle-weight-and-request-info?req-code=";
        string urlDc = "https://portal.utopiaindustries.pk/uind/rest/uic/dispatch-challan-weight-info/save-details";
        string urlGetVehicle = $"https://portal.utopiaindustries.pk/uind/rest/uic/loading-vehicle-weight-info/get-loading-vehicle-weight-and-request-info-vehicle-no?vehicle-no=";
        string urlTrolley = "https://portal.utopiaindustries.pk/uind/rest/uic/dispatch-challan-weight-info/get-trolleys";



        static MySqlConnection connection;
        private static string server;
        private static string database;
        private static string uid;
        private static string password;


        public MySqlConnection Connection()
        {
            server = "utopia-industries-rr.c5qech8o9lgg.us-east-1.rds.amazonaws.com";
            database = "inventory";
            uid = "muhammad.faique";
            password = "21)3lq6b!A@.";
            string connectionString;
            connectionString = "SERVER=" + server + ";" + "DATABASE=" +
            database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";

            connection = new MySqlConnection(connectionString);
            return connection;
        }
        public bool OpenConnection()
        {
            try
            {
                Connection();

                connection.Open();
                Console.WriteLine("Connected !");
                return true;

            }
            catch (MySqlException ex)
            {
                switch (ex.Number)
                {
                    case 0:
                        Console.WriteLine("Cannot connect to server.  Contact administrator");
                        break;

                    case 1045:
                        Console.WriteLine("Invalid username/password, please try again");
                        break;
                }
                return false;
            }
        }


        public bool CloseConnection()
        {
            try
            {
                Connection();

                connection.Close();
                return true;
            }
            catch (MySqlException ex)

            {
                Console.WriteLine(ex.Message);
                return false;
            }
        }

        public async Task<string> postDataAsyncWithoutFMS(string vehicleNo, Int32 weight, string date, string typee, string comment, Int32 userid, string siteID, string item, string transporter, string location,string  container_no)
        {
            try
            {
                DateTime parsedDate = DateTime.ParseExact(date, "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
                string convertedDate = parsedDate.ToString("yyyy-MM-ddTHH:mm");

                // Ensure TLS 1.2 is used
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

                HttpClient client = new HttpClient();
                client.Timeout = TimeSpan.FromMinutes(1);

                // Serialize the data to JSON
                // Create an anonymous object to hold the data


                string siteNumberStr = siteID.Substring(siteID.IndexOf('-') + 1);

                // Convert to integer
                int siteNumber = int.Parse(siteNumberStr);
                var data = new
                {
                    type = typee,
                    vehicleNo = vehicleNo,
                    weight = weight,
                    userId = userid,
                    dateTime = convertedDate,
                    comment = comment,
                    siteId = siteNumberStr,
                    productCode = item,
                    transporterCode = transporter,
                    partyCode = location,
                    containerNo = container_no
                };

                // Convert the data object to a JSON string
                string jsonData = JsonConvert.SerializeObject(data);

                // Create a StringContent object with JSON data
                var content = new StringContent(jsonData, Encoding.UTF8, "application/json");

                // Send a POST request with the data
                //var response = await client.PostAsync(POST_END_POINT_URL, content);
                var response = await client.PostAsync(POST_END_POINT_URL, content);

                if (response.IsSuccessStatusCode)
                {
                    // Handle a successful response
                    string responseString = await response.Content.ReadAsStringAsync();
                    return responseString;
                }
                else

                {
                    string responseString = await response.Content.ReadAsStringAsync();
                    // Handle an unsuccessful response
                    return responseString;
                }
            }
            catch (Exception ex)
            {
                return "Error";
            }
        }



        //public async Task<string> postDataWithoutFMS(string vehicleNO, string weightText, string dateText, string type, string comment, Int32 userid, string item, string transporter, string location, string site_id)
        //{
        //    try
        //    {
        //        int deadWeight = 0;
        //        int finalWeight = 0;
        //        DateTime deadWeightDateTime = DateTime.MinValue;
        //        DateTime finalWeightDateTime = DateTime.MinValue;
        //        int netWeight = 0;

        //        // Determine whether we are working with dead weight or final weight
        //        if (type == "1")
        //        {
        //            // Dead weight logic
        //            deadWeight = Convert.ToInt32(weightText);
        //            deadWeightDateTime = Convert.ToDateTime(dateText);
        //        }
        //        else
        //        {
        //            // Final weight logic
        //            finalWeight = Convert.ToInt32(weightText);
        //            finalWeightDateTime = Convert.ToDateTime(dateText);

        //            // Assuming you have dead weight already stored somewhere, calculate net weight
        //            // For simplicity, we'll subtract deadWeight from finalWeight
        //            // Replace this with actual logic if needed
        //            netWeight = finalWeight - deadWeight;
        //        }

        //        // Preparing the SQL query to insert data into the table
        //        string query = @"INSERT INTO loading_vehicle_weight_info 
        //                (type, vehicle_request_code, dead_weight, final_weight, 
        //                 dead_weight_datetime, final_weight_datetime, user_id, 
        //                 net_weight, comment,site_id,vehicle_no,party_code,transporter_code,product_code,is_fms) 
        //                VALUES (@Type, @VehicleRequestCode, @DeadWeight, @FinalWeight, 
        //                        @DeadWeightDateTime, @FinalWeightDateTime, @UserId, 
        //                        @NetWeight, @Comment,@site_id,@vehicle_no,@party_code,@transporter_code,@product_code,1)";

        //        // Preparing parameters for the query
        //        var parameters = new MySqlParameter[]
        //        {
        //    new MySqlParameter("@Type", Convert.ToInt32(type)),
        //    new MySqlParameter("@VehicleRequestCode", vehicleNO+"-"+DateTime.Now),
        //    new MySqlParameter("@DeadWeight", deadWeight),
        //    new MySqlParameter("@FinalWeight", finalWeight),
        //    new MySqlParameter("@DeadWeightDateTime", deadWeightDateTime != DateTime.MinValue ? (object)deadWeightDateTime : DBNull.Value),
        //    new MySqlParameter("@FinalWeightDateTime", finalWeightDateTime != DateTime.MinValue ? (object)finalWeightDateTime : DBNull.Value),
        //    new MySqlParameter("@UserId", userid),
        //    new MySqlParameter("@NetWeight", netWeight),
        //    new MySqlParameter("@Comment", comment),
        //    new MySqlParameter("@site_id", site_id),
        //    new MySqlParameter("@vehicle_no", vehicleNO),
        //    new MySqlParameter("@party_code", comment),
        //    new MySqlParameter("@transporter_code", userid),
        //    new MySqlParameter("@product_code", netWeight)

        //        };

        //        // Execute the query using your data access object
        //        int result = await ExecuteNonQuery(query, parameters);

        //        return result > 0 ? "Success" : "false";
        //    }
        //    catch (Exception ex)
        //    {
        //        // Log the exception or handle it as needed             
        //        return "false";
        //    }
        //}
        public async Task<int> ExecuteNonQuery(string query, MySqlParameter[] parameters)
        {
            try
            {
                await connection.OpenAsync();
                using (MySqlCommand command = new MySqlCommand(query, connection))
                {
                    command.Parameters.AddRange(parameters);
                    return await command.ExecuteNonQueryAsync();
                }

            }
            catch (Exception ex)
            {
                // Log the exception or handle it as needed
                return -1; // Return a negative value to indicate failure
            }
        }
        public async Task<string> postDataAsync(string fmsId, Int32 weight, string date, string typee, string comment, Int32 userid, string siteID,string container_no)
        {
            try
            {
                DateTime parsedDate = DateTime.ParseExact(date, "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
                string convertedDate = parsedDate.ToString("yyyy-MM-ddTHH:mm");

                // Ensure TLS 1.2 is used
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

                HttpClient client = new HttpClient();
                client.Timeout = TimeSpan.FromMinutes(5);

                // Serialize the data to JSON
                // Create an anonymous object to hold the data
                var data = new
                {
                    type = typee,
                    vehicleRequestCode = fmsId,
                    weight = weight,
                    userId = userid,
                    dateTime = convertedDate,
                    comment = comment,
                    siteID = siteID,
                    container_no = container_no

                };

                // Convert the data object to a JSON string
                string jsonData = JsonConvert.SerializeObject(data);

                // Create a StringContent object with JSON data
                var content = new StringContent(jsonData, Encoding.UTF8, "application/json");

                // Send a POST request with the data
                //var response = await client.PostAsync(POST_END_POINT_URL, content);
                var response = await client.PostAsync(POST_END_POINT_URL, content);

                if (response.IsSuccessStatusCode)
                {
                    // Handle a successful response
                    string responseString = await response.Content.ReadAsStringAsync();
                    return responseString;
                    
                }
                else
                {
                    string responseString = await response.Content.ReadAsStringAsync();
                    // Handle an unsuccessful response
                    return responseString;
                }
            }
            catch (Exception ex)
            {
                return "false";
            }
        }

        public async Task<VehicleRequestApiResponse> GetRegNo(string FmsID)
        {
            try
            {
                BusinessLayer businessLayer = new BusinessLayer();

                // Ensure TLS 1.2 is used
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

                using (HttpClient client = new HttpClient())
                {
                    client.Timeout = TimeSpan.FromMinutes(5);
                    string parameter = $"{FmsID}";

                   // var response = await client.GetAsync($"{GET_END_POINT_URL}{parameter}");
                    var response = await client.GetAsync($"{GET_END_POINT_URL}{parameter}");
                    string responseString = await response.Content.ReadAsStringAsync();


                    if (!responseString.Contains("vehicleRequest"))
                    {
                        return new VehicleRequestApiResponse
                        {
                            // Set error properties accordingly
                        };
                    }
                    else
                    {
                        // Deserialize the JSON response into ApiResponse object
                        VehicleRequestApiResponse apiResponse = JsonConvert.DeserializeObject<VehicleRequestApiResponse>(responseString);

                        return apiResponse;
                    }
                }
            }
            catch (Exception ex)
            {
                return new VehicleRequestApiResponse
                {
                    // Set error properties accordingly
                };
            }
        }

        public async Task<string> StoreWeightAgainstAPI(string qrCode, decimal weight, int trolleyId)
        {
            try
            {
                HttpClient _httpClient = new HttpClient();


                var payload = new
                {
                    code = qrCode.ToUpper(),
                    totalWeight = weight,
                    trolleyId = trolleyId
                };

                // Convert payload to JSON
                string jsonData = JsonConvert.SerializeObject(payload);

                // Create StringContent with JSON payload
                var content = new StringContent(jsonData, Encoding.UTF8, "application/json");

                // Send the POST request
                var response = await _httpClient.PostAsync(urlDc, content); // _httpClient should be your initialized HttpClient instance

                // Check the status of the response
                if (response.IsSuccessStatusCode)
                {
                    // Optionally, handle the response content
                    string responseString = await response.Content.ReadAsStringAsync();
                    return responseString;
                }
                else
                {
                    // Log the error or handle it in some way
                    string responseString = await response.Content.ReadAsStringAsync();

                    return responseString;
                }
            }
            catch (Exception ex)
            {
                // Log the exception or show a message to the user

                return "Exception";
            }
        }

        public async Task<string> GetTrolleyApi()
        {
            try
            {
                using (HttpClient _httpClient = new HttpClient())
                {
                   

                    // If no payload is required, you can send an empty POST request by passing an empty StringContent
                    var content = new StringContent(string.Empty, Encoding.UTF8, "application/json");

                    // Send the POST request
                    var response = await _httpClient.GetAsync(urlTrolley);

                    // Check the status of the response
                    if (response.IsSuccessStatusCode)
                    {
                        // Return the response content as string
                        string responseString = await response.Content.ReadAsStringAsync();
                        return responseString;
                    }
                    else
                    {
                        // Handle and return the error message
                        string responseString = await response.Content.ReadAsStringAsync();
                        return $"Error: {response.StatusCode} - {responseString}";
                    }
                }
            }
            catch (HttpRequestException httpEx)
            {
                // Handle HTTP-specific exceptions
                return $"HttpRequestException: {httpEx.Message}";
            }
            catch (Exception ex)
            {
                // Handle general exceptions
                return $"Exception: {ex.Message}";
            }
        }


        public async Task<string> GetVehicleDetails(string vehicleNO)
        {
            try
            {
                // Reuse HttpClient if possible, for performance reasons
                using (HttpClient _httpClient = new HttpClient())
                {
                    // Append the vehicle number to the URL
            
                  
                    // Send the GET request
                    var response = await _httpClient.GetAsync(urlGetVehicle+ vehicleNO);

                    // Check if the response is successful
                    if (response.IsSuccessStatusCode)
                    {
                        // Return the response content as string
                        string responseString = await response.Content.ReadAsStringAsync();
                        return responseString;
                    }
                    else
                    {
                        // Return error details if the response is not successful
                        string responseString = await response.Content.ReadAsStringAsync();
                        return $"Error: {response.StatusCode} - {responseString}";
                    }
                }
            }
            catch (HttpRequestException httpEx)
            {
                // Handle HTTP-specific exceptions
                return $"HttpRequestException: {httpEx.Message}";
            }
            catch (Exception ex)
            {
                // Handle general exceptions
                return $"Exception: {ex.Message}";
            }
        }

        public DataTable GetWeightScaleData(string tableName)
        {
            DataTable dt = new DataTable();
            try
            {
                OpenConnection();
                string query = $"SELECT * FROM {tableName}";
                using (MySqlCommand cmd = new MySqlCommand(query, connection))
                {
                    using (MySqlDataAdapter da = new MySqlDataAdapter(cmd))
                    {
                        da.Fill(dt);
                    }
                    // Add a "Select" option at the 0 index
                    DataRow newRow = dt.NewRow();
                    newRow[0] = 0; // Assuming the first column is an ID or similar
                    newRow[1] = "Select"; // Assuming the second column is the name or description
                    dt.Rows.InsertAt(newRow, 0); // Insert the new row at the first position (index 0)
                }
            }
            catch (Exception ex)
            {
                // Handle exception (log it, rethrow it, etc.)
                Console.WriteLine(ex.Message);
            }
            finally
            {
                CloseConnection();
            }
            return dt;
        }
       
        public void AddValueToDatabase(string newValue, string tableName, string columnName)
        {
            // Open the database connection
            OpenConnection();

            // Construct the query with dynamic table and column names
            string query = $"INSERT INTO `{tableName}` (`{columnName}`) VALUES (@Value)";

            try
            {
                using (MySqlCommand cmd = new MySqlCommand(query, connection))
                {
                    // Add the parameter value
                    cmd.Parameters.AddWithValue("@Value", newValue);

                    // Execute the query
                    cmd.ExecuteNonQuery();
                }
            }
            catch (MySqlException ex)
            {
               // MessageBox.Show($"Error while adding value: {ex.Message}", "Database Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // Close the connection to avoid resource leaks
                CloseConnection();
            }
        }

    }
}

