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

namespace TimelogBackend;

public class TopTen
{
    public object? User { get; set; }
    public object? Date { get; set; }
    public object? Project { get; set; }
    public object? FName { get; set; }
    public object? LName { get; set; }
    public object? Name { get; set; }
    public object? TotalTime { get; set; }
}

public class Gettopten : Route
{
    private static List<TopTen> ExtractDataFromDB(MySqlCommand cmd)
    {
        using MySqlConnection conn = new(connectionString);
        cmd.Connection = conn;
        conn.Open();
        // Execute the query and read the results
        MySqlDataReader reader = cmd.ExecuteReader();
        List<TopTen> entries = [];
        while (reader.Read())
        {
            entries.Add(
                new TopTen
                {
                    User = reader["user"],
                    Date = reader["date"],
                    Project = reader["project"],
                    FName = reader["f_name"],
                    LName = reader["l_name"],
                    Name = reader["name"],
                    TotalTime = reader["total_time"],
                }
            );
        }
        return entries;
    }

    private static void ValidateQueryStrings(string from, string to, string filterBy)
    {
        if (!string.IsNullOrEmpty(to) && !string.IsNullOrEmpty(from))
        {
            ValidateDate(to);
            ValidateDate(from);
        }
        else
        {
            throw new Exception("Empty date format");
        }
        if (string.IsNullOrEmpty(filterBy))
        {
            throw new Exception("Empty filterby");
        }
        if (filterBy != "user" && filterBy != "project")
        {
            throw new Exception("Incorrect filterby");
        }
    }

    public static void HandleRequest(HttpListenerRequest request, HttpListenerResponse response)
    {
        try
        {
            var queryString = request.QueryString;
            string? from = queryString["from"] ?? "";
            string? to = queryString["to"] ?? "";
            string? filterBy = queryString["filterBy"] ?? "";
            ValidateQueryStrings(from, to, filterBy);
            string query =
                @"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;";
            MySqlCommand cmd = new(query);
            cmd.Parameters.AddWithValue("@from", from);
            cmd.Parameters.AddWithValue("@to", to);

            var entries = ExtractDataFromDB(cmd);
            string jsonResponse = JsonConvert.SerializeObject(entries);
            SendSuccess(response, jsonResponse);
        }
        catch (Exception ex)
        {
            SendError(response, ex);
        }
    }
}
