/**
 * Namf_Communication
 * AMF Communication 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.
 */

#include "N1N2SubscriptionsCollectionForIndividualUEContextsDocumentApiImpl.h"

#include "3gpp_29.500.h"
#include "itti.hpp"

extern itti_mw* itti_inst;
namespace oai {
namespace amf {
namespace api {

using namespace oai::amf::model;

N1N2SubscriptionsCollectionForIndividualUEContextsDocumentApiImpl::
    N1N2SubscriptionsCollectionForIndividualUEContextsDocumentApiImpl(
        std::shared_ptr<Pistache::Rest::Router> rtr,
        amf_application::amf_app* amf_app_inst)
    : N1N2SubscriptionsCollectionForIndividualUEContextsDocumentApi(rtr),
      m_amf_app(amf_app_inst) {}

void N1N2SubscriptionsCollectionForIndividualUEContextsDocumentApiImpl::
    n1_n2_message_subscribe(
        const std::string& ueContextId,
        const UeN1N2InfoSubscriptionCreateData&
            ueN1N2InfoSubscriptionCreateData,
        Pistache::Http::ResponseWriter& response) {
  Logger::amf_server().debug("Receive N1N2MessageSubscribe, handling...");
  Logger::amf_server().debug("UE Context ID (%s)", ueContextId.c_str());

  // Generate a promise and associate this promise to the ITTI message
  uint32_t promise_id = m_amf_app->generate_promise_id();
  Logger::amf_n1().debug("Promise ID generated %d", promise_id);

  boost::shared_ptr<boost::promise<nlohmann::json>> p =
      boost::make_shared<boost::promise<nlohmann::json>>();
  boost::shared_future<nlohmann::json> f = p->get_future();
  m_amf_app->add_promise(promise_id, p);

  // Handle the N1N2SubscribeMessage in amf_app
  std::shared_ptr<itti_sbi_n1n2_message_subscribe> itti_msg =
      std::make_shared<itti_sbi_n1n2_message_subscribe>(
          TASK_AMF_SBI, TASK_AMF_APP, promise_id);

  itti_msg->ue_cxt_id         = ueContextId;
  itti_msg->subscription_data = ueN1N2InfoSubscriptionCreateData;
  itti_msg->http_version      = 1;
  itti_msg->promise_id        = promise_id;

  int ret = itti_inst->send_msg(itti_msg);
  if (0 != ret) {
    Logger::amf_server().error(
        "Could not send ITTI message %s to task TASK_AMF_APP",
        itti_msg->get_msg_name());
  }

  boost::future_status status;
  // wait for timeout or ready
  status = f.wait_for(boost::chrono::milliseconds(FUTURE_STATUS_TIMEOUT_MS));
  if (status == boost::future_status::ready) {
    assert(f.is_ready());
    assert(f.has_value());
    assert(!f.has_exception());
    // Wait for the result from APP and send reply to AMF
    // result includes location, UeN1N2InfoSubscriptionCreatedData, and http
    // response code
    nlohmann::json result = f.get();
    Logger::amf_server().debug("Got result for promise ID %d", promise_id);

    // process data
    std::string location        = {};
    uint32_t http_response_code = 0;
    if (result.find("location") != result.end()) {
      location = result["location"].get<std::string>();
    }

    if (result.find("httpResponseCode") != result.end()) {
      http_response_code = result["httpResponseCode"].get<int>();
    }

    // UeN1N2InfoSubscriptionCreatedData
    nlohmann::json json_data = {};
    if (result.find("createdData") != result.end()) {
      json_data = result["createdData"];
    }

    if (static_cast<http_response_codes_e>(http_response_code) ==
        http_response_codes_e::HTTP_RESPONSE_CODE_201_CREATED) {
      response.headers().add<Pistache::Http::Header::Location>(
          location);  // Location header
      response.headers().add<Pistache::Http::Header::ContentType>(
          Pistache::Http::Mime::MediaType("application/json"));
      response.send(Pistache::Http::Code::Created, json_data.dump().c_str());
    } else {
      response.send(Pistache::Http::Code(http_response_code));
    }
  }
}

}  // namespace api
}  // namespace amf
}  // namespace oai
