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

namespace Server
{
    public class TopTen
    {
        public object? user { get; set; }
        public object? date { get; set; }
        public object? project { get; set; }
        public object? f_name { get; set; }
        public object? l_name { get; set; }
        public object? name { get; set; }
        public object? total_time { get; set; }
    }
    public class Gettopten
    {
        public static void run(MySqlConnection conn, HttpListenerRequest request, HttpListenerResponse response)
        {
            try
            {
                // open db connection
                conn.Open();
                // prepare SQL query
                MySqlCommand cmd = new MySqlCommand();
                cmd.Connection = conn;
                var queryString = request.QueryString;
                string? from = queryString["from"];
                string? to = queryString["to"];
                string? filterBy = queryString["filterBy"];
                // this shenanigan is needed to remove the "" around
                // group by
                string req = @"SELECT t.user,t.date,t.project,u.f_name,u.l_name,p.name,SUM(t.time) as total_time 
                               FROM Timelog t 
                               INNER JOIN Project p ON p.id=t.project 
                               INNER JOIN User u ON u.id=t.user 
                               WHERE t.date BETWEEN @from AND @to
                               GROUP BY " + filterBy + @" ORDER BY total_time DESC 
                               LIMIT 10;";
                cmd.CommandText = req;
                cmd.Parameters.AddWithValue("@from", from);
                cmd.Parameters.AddWithValue("@to", to);

                // Execute the query and read the results
                MySqlDataReader reader = cmd.ExecuteReader();
                List<TopTen> entries = new List<TopTen>();
                while (reader.Read())
                {
                    entries.Add(new TopTen
                    {
                        user = reader["user"],
                        date = reader["date"],
                        project = reader["project"],
                        f_name = reader["f_name"],
                        l_name = reader["l_name"],
                        name = reader["name"],
                        total_time = reader["total_time"],
                    });
                }
                // 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)
            {
                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();
            }
        }
    }
}
