/*
 * Licensed to Open Source Radio Access Network(OS-RAN) Alliance and OAI
 * Software Alliance under one or more contributor license agreements. The
 * initial OpenXG series projects are derided from OAI projects, the files from
 * OAI projects are all in compliance with OAI Public License, Version 1.1.
 * codes and files developed from OpenXG projects and from OS-RAN Alliance
 * are all under OS-RAN licenses; you may not use this file except in compliance
 * with the license.  You may get a copy of the license at:
 *	http://www.openxg.org.cn/?falu_69.html
 * For more information about OpenXG, please contact:
 * contact@openxg.org.cn
 */

#include "smf-api-server.h"
#include "pistache/endpoint.h"
#include "pistache/http.h"
#include "pistache/router.h"
#ifdef __linux__
#include <vector>
#include <signal.h>
#include <unistd.h>
#endif

#define PISTACHE_SERVER_MAX_PAYLOAD 32768

#ifdef __linux__
void sigHandler(int sig) {
  switch (sig) {
    case SIGINT:
    case SIGQUIT:
    case SIGTERM:
    case SIGHUP:
    default:
      break;
  }
  exit(0);
}

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 oai::smf_server::api;

void SMFApiServer::init(size_t thr) {
  auto opts = Pistache::Http::Endpoint::options().threads(thr);
  opts.flags(Pistache::Tcp::Options::ReuseAddr);
  opts.maxRequestSize(PISTACHE_SERVER_MAX_PAYLOAD);
  m_httpEndpoint->init(opts);
  m_individualPDUSessionHSMFApiImpl->init();
  m_individualSMContextApiImpl->init();
  m_pduSessionsCollectionApiImpl->init();
  m_smContextsCollectionApiImpl->init();
  m_individualSubscriptionDocumentApiImpl->init();
  m_subscriptionsCollectionApiImpl->init();
  m_nfStatusNotifyApiImpl->init();
  m_smfToDataApiImpl->init();
  
}
void SMFApiServer::start() {
  Logger::smf_api_server().info("HTTP1 server started");
  m_httpEndpoint->setHandler(m_router->handler());
  m_httpEndpoint->serve();
}
void SMFApiServer::shutdown() {
  m_httpEndpoint->shutdown();
}
