/**
 * Nsmf_PDUSession
 * SMF PDU Session Service. © 2019, 3GPP Organizational Partners (ARIB, ATIS,
 * CCSA, ETSI, TSDSI, TTA, TTC). All rights reserved.
 *
 * The version of the OpenAPI document: 1.1.0.alpha-1
 *
 *
 * NOTE: This class is auto generated by OpenAPI Generator
 * (https://openapi-generator.tech). https://openapi-generator.tech Do not edit
 * the class manually.
 */

/*
 * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The OpenAirInterface Software Alliance licenses this file to You under
 * the OAI Public License, Version 1.1  (the "License"); you may not use this
 * file except in compliance with the License. You may obtain a copy of the
 * License at
 *
 *      http://www.openairinterface.org/?page_id=698
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *-------------------------------------------------------------------------------
 * For more information about the OpenAirInterface (OAI) Software Alliance:
 *      contact@openairinterface.org
 */

#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
