/**
 * 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 "logger.hpp"
#include "Helpers.h"
extern "C" {
#include "multipartparser.h"
}

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

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 + "/sm-contexts", 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().info("\nReceived a SM context create request from AMF");
  Logger::smf_api_server().debug("Request body: %s",request.body().c_str());

  //find boundary
  std::size_t found = request.body().find("Content-Type");
  std::string boundary_str = request.body().substr(2, found - 4);
  Logger::smf_api_server().debug("Boundary: %s", boundary_str.c_str());

  SmContextMessage smContextMessage = {};
  SmContextCreateData smContextCreateData = {};

  //step 1. use multipartparser to decode the request
  multipartparser_callbacks_init(&g_callbacks);
  g_callbacks.on_body_begin = &on_body_begin;
  g_callbacks.on_part_begin = &on_part_begin;
  g_callbacks.on_header_field = &on_header_field;
  g_callbacks.on_header_value = &on_header_value;
  g_callbacks.on_headers_complete = &on_headers_complete;
  g_callbacks.on_data = &on_data;
  g_callbacks.on_part_end = &on_part_end;
  g_callbacks.on_body_end = &on_body_end;

  multipartparser parser = {};
  init_globals();
  multipartparser_init(&parser, reinterpret_cast<const char*>(boundary_str.c_str()));
  if ((multipartparser_execute(&parser, &g_callbacks, request.body().c_str(), strlen(request.body().c_str())) != strlen(request.body().c_str())) or (!g_body_begin_called)){
	  Logger::smf_api_server().warn("The received message can not be parsed properly!");
	  //TODO: fix this issue
	  //response.send(Pistache::Http::Code::Bad_Request, "");
    //return;
  }

  Logger::smf_api_server().debug("Number of g_parts %d", g_parts.size());
  //at least 2 parts for Json data and N1 (+ N2)
  if (g_parts.size() < 2){
    response.send(Pistache::Http::Code::Bad_Request, "");
    return;
  }

  part p0 = g_parts.front(); g_parts.pop_front();
  Logger::smf_api_server().debug("Request body, part 1: \n%s", p0.body.c_str());
  part p1 = g_parts.front(); g_parts.pop_front();
  Logger::smf_api_server().debug("Request body, part 2: \n %s",p1.body.c_str());
  if (g_parts.size() > 0) {
    part p2 = g_parts.front(); g_parts.pop_front();
    Logger::smf_api_server().debug("Request body, part 3: \n %s",p2.body.c_str());
  }

  //step 2. process the request
  try {
    nlohmann::json::parse(p0.body.c_str()).get_to(smContextCreateData);
    smContextMessage.setJsonData(smContextCreateData);
    smContextMessage.setBinaryDataN1SmMessage(p1.body.c_str());
    this->post_sm_contexts(smContextMessage, response);
  } catch (nlohmann::detail::exception &e) {
    //send a 400 error
	  Logger::smf_api_server().warn("Can not parse the json data (error: %s)!", e.what());
	  response.send(Pistache::Http::Code::Bad_Request, e.what());
    return;
  } catch (std::exception &e) {
    //send a 500 error
    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");
}

}
}
}

