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

namespace Server;

public class Getuser : Route
{
    public static void HandleRequest(HttpListenerRequest request, HttpListenerResponse response)
    {
        try
        {
            var queryString = request.QueryString;
            string? userid = queryString["userid"];
            if (string.IsNullOrEmpty(userid))
            {
                throw new Exception("Missing userid");
            }
            // prepare SQL query
            MySqlCommand cmd = new()
            {
                CommandText =
                    @"SELECT p.name, SUM(t.time)
                                    FROM Timelog t 
                                    INNER JOIN Project p ON p.id=t.project 
                                    INNER JOIN User u ON u.id=t.user 
                                    WHERE User = @userid
                                    GROUP BY name;",
            };
            cmd.Parameters.AddWithValue("@userid", userid);

            using (MySqlConnection conn = new(connectionString))
            {
                conn.Open();
                cmd.Connection = conn;
                // execute query and read results
                MySqlDataReader reader = cmd.ExecuteReader();
                dynamic expando = new ExpandoObject();
                while (reader.Read())
                {
                    ((IDictionary<string?, object>)expando)[reader["name"].ToString()] = reader[
                        "SUM(t.time)"
                    ];
                }
                // serialize JSON
                string jsonResponse = JsonConvert.SerializeObject(expando);
                // prepare response
                SendSuccess(response, jsonResponse);
            }
        }
        catch (Exception ex)
        {
            SendError(response, ex);
        }
    }
}
