using System;
using System.Net;
using System.Text;
using System.Threading;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using System.Collections.Generic;

class Program
{
  static void Main()
  {
    // Create an HttpListener to handle incoming HTTP requests
    HttpListener listener = new HttpListener();

    // Add a prefix to listen to, e.g., http://localhost:8080/
    listener.Prefixes.Add("http://localhost:5000/");

    // Start listening for incoming requests
    listener.Start();
    Console.WriteLine("Server is listening on http://localhost:5000/");

    // Handle requests on a separate thread to keep server responsive
    Thread listenerThread = new Thread(() =>
    {
      while (true)
      {
        // Wait for a request
        HttpListenerContext context = listener.GetContext();
        // Get the request and response objects
        HttpListenerRequest request = context.Request;
        HttpListenerResponse response = context.Response;
        // Check if the requested URL is /api
        if (request.Url.AbsolutePath == "/api")
        {
          string connectionString = "Server=localhost;Port=5050;Database=your_database;User ID=your_user;Password=your_password;";
          MySqlConnection conn = new MySqlConnection(connectionString);

          try
          {
            // Open the connection
            conn.Open();

            // Prepare the SQL query
            string query = "SELECT * FROM User;";
            MySqlCommand cmd = new MySqlCommand(query, conn);

            // Execute the query and read the results
            MySqlDataReader reader = cmd.ExecuteReader();
            StringBuilder result = new StringBuilder();

            while (reader.Read())
            {
              // Assuming User table has columns "id", "name", and "email"
              result.AppendLine($"ID: {reader["id"]}, Name: {reader["name"]}, Email: {reader["email"]}");
              // Prepare the response message
              string responseMessage = result.ToString();


              if (string.IsNullOrEmpty(responseMessage))
              {
                responseMessage = "No data found.";
              }

              byte[] buffer = Encoding.UTF8.GetBytes(responseMessage);

              // Set the response content type and write the response
              response.ContentType = "text/plain";
              response.ContentLength64 = buffer.Length;
              response.OutputStream.Write(buffer, 0, buffer.Length);
            }
          catch (Exception ex)
          {
            // Handle any connection errors
            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 the connection
            conn.Close();
          }

        }
        else
        {
          // Return 404 for other paths
          response.StatusCode = 404;
          string errorMessage = "Not Found";
          byte[] buffer = Encoding.UTF8.GetBytes(errorMessage);
          response.ContentType = "text/plain";
          response.ContentLength64 = buffer.Length;
          response.OutputStream.Write(buffer, 0, buffer.Length);
        }

        // Close the response
        response.OutputStream.Close();
      }
    });

    // Start the listener thread
    listenerThread.Start();
  }
}

