#include "HttpServer.h"

using namespace std;
//--------------------------------------------------------------
/* Default destructor */
HttpServer::~HttpServer()
{
  // Ensure the server is stopped and resources are cleaned up
  disable();
}
//--------------------------------------------------------------
/* Start the server and listen on the specified address and port */
void HttpServer::enable(const std::string &listenAddresses, uint16_t listenPort)
{
  scoped_lock lock(m_httpServer.serverMtx);
  if (m_httpServer.hServer)
    return;     // Server is already running, no need to start it again

  // Create a new instance of the HTTP server
  m_httpServer.hServer = make_unique<httplib::Server>();

  // Define a simple GET endpoint that responds with "Hello World!" when accessed
  m_httpServer.hServer->Get("/hi", [](const httplib::Request &, httplib::Response &res)
                            { res.set_content("Hello World!", "text/plain"); });

  // Start the listening thread for the server
  m_httpServer.serverThread = std::jthread([this, listenAddresses, listenPort]()
                                           {
        // Start listening on the specified address and port
        m_httpServer.hServer->listen(listenAddresses, listenPort); });
}
//--------------------------------------------------------------
/* Stop the server and clean up resources */
void HttpServer::disable()
{
  scoped_lock lock(m_httpServer.serverMtx);
  if (!m_httpServer.hServer)
    return;     // Server is not running, no need to stop it

  // Stop the server and wait for the listening thread to finish
  m_httpServer.hServer->stop();
  if (m_httpServer.serverThread.joinable())
    m_httpServer.serverThread.join();

  // Reset the server instance to release resources
  m_httpServer.hServer.reset();
}
//--------------------------------------------------------------
/* Check if the server is currently enabled */
bool HttpServer::isEnabled()
{
  scoped_lock lock(m_httpServer.serverMtx);
  return m_httpServer.hServer != nullptr;
}
//--------------------------------------------------------------
