/*
 * 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 "SMContextsCollectionApi.h"

#include <cassert>
#include <cstring>
#include <cstdio>
#include <iostream>
#include <list>
#include <map>
#include <string>

#include "logger.hpp"
#include "Helpers.h"
#include "mime_parser.hpp"
#include "smf_config.hpp"

extern smf::smf_config smf_cfg;

namespace oai {
namespace smf_server {
namespace api {

using namespace oai::smf_server::helpers;
using namespace oai::smf_server::model;

SMContextsCollectionApi::SMContextsCollectionApi(
    std::shared_ptr<Pistache::Rest::Router> rtr) {
  router = rtr;
}

void SMContextsCollectionApi::init() {
  setupRoutes();
}

void SMContextsCollectionApi::setupRoutes() {
  using namespace Pistache::Rest;

  Routes::Post(
      *router,
      base + smf_cfg.sbi_api_version + NSMF_PDU_SESSION_SM_CONTEXT_CREATE_URL,
      Routes::bind(&SMContextsCollectionApi::post_sm_contexts_handler, this));

  // Default handler, called when a route is not found
  router->addCustomHandler(Routes::bind(
      &SMContextsCollectionApi::sm_contexts_collection_api_default_handler,
      this));
}

void SMContextsCollectionApi::post_sm_contexts_handler(
    const Pistache::Rest::Request& request,
    Pistache::Http::ResponseWriter response) {
  Logger::smf_api_server().debug("");
  Logger::smf_api_server().info(
      "Received a SM context create request from AMF.");
  SmContextMessage smContextMessage       = {};
  SmContextCreateData smContextCreateData = {};

  // simple parser
  mime_parser sp = {};
  sp.parse(request.body());

  std::vector<mime_part> parts = {};
  sp.get_mime_parts(parts);
  uint8_t size = parts.size();
  Logger::smf_api_server().debug("Number of MIME parts %d", size);
  // at least 2 parts for Json data and N1 (+ N2)
  if (size < 2) {
    response.send(Pistache::Http::Code::Bad_Request);
    return;
  }

  // step 2. process the request
  try {
    nlohmann::json::parse(parts[0].body.c_str()).get_to(smContextCreateData);
    smContextMessage.setJsonData(smContextCreateData);
    // must include N1 NAS msg
    if (parts[1].content_type.compare("application/vnd.3gpp.5gnas") == 0) {
      smContextMessage.setBinaryDataN1SmMessage(parts[1].body);
    } else {
      response.send(Pistache::Http::Code::Bad_Request);
      return;
    }

    this->post_sm_contexts(smContextMessage, response);

  } catch (nlohmann::detail::exception& e) {
    Logger::smf_api_server().warn(
        "Cannot parse the json data (error: %s)!", e.what());
    response.send(Pistache::Http::Code::Bad_Request, e.what());
    return;
  } catch (std::exception& e) {
    Logger::smf_api_server().warn("Error: %s!", e.what());
    response.send(Pistache::Http::Code::Internal_Server_Error, e.what());
    return;
  }
}

void SMContextsCollectionApi::sm_contexts_collection_api_default_handler(
    const Pistache::Rest::Request&, Pistache::Http::ResponseWriter response) {
  response.send(
      Pistache::Http::Code::Not_Found, "The requested method does not exist");
}

}  // namespace api
}  // namespace smf_server
}  // namespace oai
