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

namespace Server
{
    public class Getuser
    {
        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;
                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);
                // 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
                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
            {
                // close db connection
                conn.Close();
            }
        }
    }
}

