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

namespace Server
{
    // there should be a better way to deal with data comming from sql
    public class Log
    {
        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 connection
                conn.Open();
                // prepare SQL query
                MySqlCommand cmd = new MySqlCommand();
                cmd.Connection = conn;
                // get url params
                var queryString = request.QueryString;
                string? from = queryString["from"];
                string? to = queryString["to"];
                string? sortby = queryString["sortby"];
                string? offset = queryString["offset"];
                string? order = queryString["order"];
                order = order == "true" ? "ASC" : "DESC";
                // 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 + ";";
                // depending on the incoming parameters construct a Query
                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 + " " + order;
                    sqlQ = sqlQ + orderQ;
                }
                // add the final line to the query
                cmd.CommandText = sqlQ + offsetQ;
                // those don't produce error if they don't find their variables
                cmd.Parameters.AddWithValue("@from", from);
                cmd.Parameters.AddWithValue("@to", to);

                // execute query and read results
                MySqlDataReader reader = cmd.ExecuteReader();

                List<Log> entries = new List<Log>();
                while (reader.Read())
                {
                    entries.Add(new Log
                    {
                        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 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)
            {
                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);
            }
            finally
            {
                conn.Close();
            }
        }
    }
}
