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

namespace Server
{
    public class Getuser : Route
    {
        public static void HandleRequest(HttpListenerRequest request, HttpListenerResponse response)
        {

            try
            {
                // prepare SQL query
                MySqlCommand cmd = new MySqlCommand();
                cmd.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;";
                var queryString = request.QueryString;
                string? userid = queryString["userid"];
                cmd.Parameters.AddWithValue("@userid", userid);

                using (MySqlConnection conn = new MySqlConnection(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);
            }
        }
    }
}

