using System;
using System.Net;
using System.Text;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;

namespace Server
{
    public class All
    {
        public object f_name { get; set; }
        public object l_name { get; set; }
        public object mail { get; set; }
        public object name { get; set; }
        public object time { get; set; }
        public object date { get; set; }
        public object user { get; set; }
    }

    public class Getall
    {
        public static void run(MySqlConnection conn, HttpListenerRequest request, HttpListenerResponse response)
        {
            try
            {
                // Open the connection
                conn.Open();
                // Prepare the SQL query
                MySqlCommand myCommand = new MySqlCommand();
                myCommand.Connection = conn;
                var queryString = request.QueryString;
                string from = queryString["from"];
                string to = queryString["to"];
                string sortby = queryString["sortby"];
                string offset = queryString["offset"];

                // this shenanigan is needed to remove the "" around
                // group by
                string sqlQ = @"SELECT u.f_name,u.l_name,u.mail,p.name,t.time,t.date,t.user 
                                        FROM Timelog t 
                                        INNER JOIN Project p ON p.id=t.project 
                                        INNER JOIN User u ON u.id=t.user ";
                string offsetQ = " LIMIT 10 OFFSET " + offset + ";";
                if (!string.IsNullOrEmpty(to) && !string.IsNullOrEmpty(from))
                {
                    string whereQ = " WHERE t.date BETWEEN @from AND @to ";
                    sqlQ = sqlQ + whereQ;
                }
                if (!string.IsNullOrEmpty(sortby))
                {
                    string orderQ = " ORDER BY " + sortby;
                    sqlQ = sqlQ + orderQ;
                }
                myCommand.CommandText = sqlQ + offsetQ;
                myCommand.Parameters.AddWithValue("@from", from);
                myCommand.Parameters.AddWithValue("@to", to);

                // Execute the query and read the results
                MySqlDataReader reader = myCommand.ExecuteReader();
                List<All> entries = new List<All>();
                while (reader.Read())
                {
                    entries.Add(new All
                    {
                        f_name = reader["f_name"],
                        l_name = reader["l_name"],
                        user = reader["user"],
                        date = reader["date"],
                        name = reader["name"],
                        time = reader["time"],
                        mail = reader["mail"],
                    });
                }
                // Serialize the data to JSON
                string jsonResponse = JsonConvert.SerializeObject(entries);
                // prepare response
                byte[] buffer = Encoding.UTF8.GetBytes(jsonResponse);
                response.ContentType = "application/json";
                response.ContentLength64 = buffer.Length;
                response.OutputStream.Write(buffer, 0, buffer.Length);

            }
            catch (Exception ex)
            {
                // Handle any connection errors
                string errorMessage = $"Error: {ex.Message}";
                byte[] buffer = Encoding.UTF8.GetBytes(errorMessage);
                response.ContentType = "text/plain";
                response.ContentLength64 = buffer.Length;
                response.OutputStream.Write(buffer, 0, buffer.Length);
            }
            conn.Close();
        }
    }
}
