#include "plugin_server.hpp"


#ifdef __linux__
static void sigHandler [[noreturn]] (int sig) {
  switch (sig) {
  case SIGINT:
  case SIGQUIT:
  case SIGTERM:
  case SIGHUP:
  default:
    //                m_httpEndpoint->shutdown();
    break;
  }
  exit(0);
}

static void setUpUnixSignals(std::vector<int> quitSignals) {
  sigset_t blocking_mask;
  sigemptyset(&blocking_mask);
  for (auto sig : quitSignals)
    sigaddset(&blocking_mask, sig);

  struct sigaction sa;
  sa.sa_handler = sigHandler;
  sa.sa_mask = blocking_mask;
  sa.sa_flags = 0;

  for (auto sig : quitSignals)
    sigaction(sig, &sa, nullptr);
}
#endif

using namespace org::openapitools::server::api;

PLUGINApiServer::PLUGINApiServer(Pistache::Address address)
    : m_httpEndpoint(std::make_shared<Pistache::Http::Endpoint>(address)) {
    m_router = std::make_shared<Pistache::Rest::Router>();


    //     std::make_shared<RecordCRUDApiImpl>(m_router,mysql);
    // m_BlockCRUDApiserver =
    //     std::make_shared<BlockCRUDApiImpl>(m_router,mysql);
    // m_MetaSchemaCRUDApiserver =
    //     std::make_shared<MetaSchemaCRUDApiImpl>(m_router);
    // m_NotificationSubscriptionCRUDApiserver =
    //     std::make_shared<NotificationSubscriptionCRUDApiImpl>(m_router);
    // m_NotificationSubscriptionsCRUDApiserver =
    //     std::make_shared<NotificationSubscriptionsCRUDApiImpl>(m_router);
    // m_RecordCRUDApiserver =
    //     std::make_shared<RecordCRUDApiImpl>(m_router,mysql);
    m_PluginApiserver =
         std::make_shared<PluginApiImpl>(m_router);

}
void PLUGINApiServer::init(size_t thr) {
#ifdef __linux__
  std::vector<int> sigs{SIGQUIT, SIGINT, SIGTERM, SIGHUP};
  setUpUnixSignals(sigs);
#endif

  auto opts = Pistache::Http::Endpoint::options().threads(thr);
  opts.flags(Pistache::Tcp::Options::ReuseAddr);
  opts.maxRequestSize(PISTACHE_SERVER_MAX_REQUEST_SIZE);
  opts.maxResponseSize(PISTACHE_SERVER_MAX_RESPONSE_SIZE);
  m_httpEndpoint->init(opts);

  m_PluginApiserver->init();

  Logger::plugin_app().debug("Initiate PLUGIN server endpoints done!\n");
}
void PLUGINApiServer::start() {


  m_httpEndpoint->setHandler(m_router->handler());
  m_httpEndpoint->serve();
}
void PLUGINApiServer::shutdown() { m_httpEndpoint->shutdown(); }