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

#include "RecordCRUDApi.h"
#include "Helpers.h"
#include "logger.hpp"
namespace org {
namespace openapitools {
namespace server {
namespace api {

using namespace org::openapitools::server::helpers;
using namespace org::openapitools::server::model;

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

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

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

    Routes::Put(*router, base + "/:realmId/:storageId/records/:recordId", Routes::bind(&RecordCRUDApi::create_or_modify_record_handler, this));
    Routes::Delete(*router, base + "/:realmId/:storageId/records/:recordId", Routes::bind(&RecordCRUDApi::delete_record_handler, this));
    Routes::Get(*router, base + "/:realmId/:storageId/records/:recordId/meta", Routes::bind(&RecordCRUDApi::get_meta_handler, this));
    Routes::Get(*router, base + "/:realmId/:storageId/records/:recordId", Routes::bind(&RecordCRUDApi::get_record_handler, this));
    Routes::Get(*router, base + "/:realmId/:storageId/records", Routes::bind(&RecordCRUDApi::search_record_handler, this));
    Routes::Patch(*router, base + "/:realmId/:storageId/records/:recordId/meta", Routes::bind(&RecordCRUDApi::update_meta_handler, this));

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

void RecordCRUDApi::create_or_modify_record_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) {
    // Getting the path params



    auto realmId = request.param(":realmId").as<std::string>();
    auto storageId = request.param(":storageId").as<std::string>();
    auto recordId = request.param(":recordId").as<std::string>();
    
    Logger::udsf_server().info("--Put!--/%s/%s/records/%s",realmId.c_str(),storageId.c_str(),recordId.c_str());
    // Getting the body param
    
    Record record;
    
    // Getting the query params
    auto getPreviousQuery = request.query().get("get-previous");
    Pistache::Optional<bool> getPrevious;
    if(!getPreviousQuery.isEmpty()){
        bool valueQuery_instance;
        if(fromStringValue(getPreviousQuery.get(), valueQuery_instance)){
            getPrevious = Pistache::Some(valueQuery_instance);
        }
    }
    auto supportedFeaturesQuery = request.query().get("supported-features");
    Pistache::Optional<std::string> supportedFeatures;
    if(!supportedFeaturesQuery.isEmpty()){
        std::string valueQuery_instance;
        if(fromStringValue(supportedFeaturesQuery.get(), valueQuery_instance)){
            supportedFeatures = Pistache::Some(valueQuery_instance);
        }
    }
    
    // Getting the header params
    auto ifNoneMatch = request.headers().tryGetRaw("If-None-Match");
    auto ifMatch = request.headers().tryGetRaw("If-Match");
    std::cout<<request.body()<<std::endl;
    try {
        //{"meta": { "tags" : {"tag1" : ["value1"], "tag2" :["value2"] } }, "blocks": [{"Content-ID": "userDefBinaryBlob", "Content-Type": "text/plain", "content": "QmxvY2sgY29udGVudA=="}, {"Content-Id": "userDefJsonBlob", "Content-Type": "application/json", "content": {"key": "ftsimpletype-999550000000002", "value": "A3E71A78377179B5B91A;imsi-999550000000123"}}]}
      nlohmann::json::parse(request.body()).get_to(record);
      this->create_or_modify_record(realmId, storageId, recordId, record, ifNoneMatch, ifMatch, getPrevious, supportedFeatures, response);
    } catch (nlohmann::detail::exception &e) {
        //send a 400 error
        response.send(Pistache::Http::Code::Bad_Request, e.what());
        return;
    } catch (Pistache::Http::HttpError &e) {
        response.send(static_cast<Pistache::Http::Code>(e.code()), e.what());
        return;
    } catch (std::exception &e) {
        //send a 500 error
        response.send(Pistache::Http::Code::Internal_Server_Error, e.what());
        return;
    }

}
void RecordCRUDApi::delete_record_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) {
    // Getting the path params
    auto realmId = request.param(":realmId").as<std::string>();
    auto storageId = request.param(":storageId").as<std::string>();
    auto recordId = request.param(":recordId").as<std::string>();
    
    // Getting the query params
    auto getPreviousQuery = request.query().get("get-previous");
    Pistache::Optional<bool> getPrevious;
    if(!getPreviousQuery.isEmpty()){
        bool valueQuery_instance;
        if(fromStringValue(getPreviousQuery.get(), valueQuery_instance)){
            getPrevious = Pistache::Some(valueQuery_instance);
        }
    }
    auto supportedFeaturesQuery = request.query().get("supported-features");
    Pistache::Optional<std::string> supportedFeatures;
    if(!supportedFeaturesQuery.isEmpty()){
        std::string valueQuery_instance;
        if(fromStringValue(supportedFeaturesQuery.get(), valueQuery_instance)){
            supportedFeatures = Pistache::Some(valueQuery_instance);
        }
    }
    
    // Getting the header params
    auto ifMatch = request.headers().tryGetRaw("If-Match");

    try {
      this->delete_record(realmId, storageId, recordId, ifMatch, getPrevious, supportedFeatures, response);
    } catch (nlohmann::detail::exception &e) {
        //send a 400 error
        response.send(Pistache::Http::Code::Bad_Request, e.what());
        return;
    } catch (Pistache::Http::HttpError &e) {
        response.send(static_cast<Pistache::Http::Code>(e.code()), e.what());
        return;
    } catch (std::exception &e) {
        //send a 500 error
        response.send(Pistache::Http::Code::Internal_Server_Error, e.what());
        return;
    }

}
void RecordCRUDApi::get_meta_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) {
    // Getting the path params
    auto realmId = request.param(":realmId").as<std::string>();
    auto storageId = request.param(":storageId").as<std::string>();
    auto recordId = request.param(":recordId").as<std::string>();
    
    // Getting the query params
    auto supportedFeaturesQuery = request.query().get("supported-features");
    Pistache::Optional<std::string> supportedFeatures;
    if(!supportedFeaturesQuery.isEmpty()){
        std::string valueQuery_instance;
        if(fromStringValue(supportedFeaturesQuery.get(), valueQuery_instance)){
            supportedFeatures = Pistache::Some(valueQuery_instance);
        }
    }
    
    // Getting the header params
    auto ifNoneMatch = request.headers().tryGetRaw("If-None-Match");
    auto ifModifiedSince = request.headers().tryGetRaw("If-Modified-Since");

    try {
      this->get_meta(realmId, storageId, recordId, ifNoneMatch, ifModifiedSince, supportedFeatures, response);
    } catch (nlohmann::detail::exception &e) {
        //send a 400 error
        response.send(Pistache::Http::Code::Bad_Request, e.what());
        return;
    } catch (Pistache::Http::HttpError &e) {
        response.send(static_cast<Pistache::Http::Code>(e.code()), e.what());
        return;
    } catch (std::exception &e) {
        //send a 500 error
        response.send(Pistache::Http::Code::Internal_Server_Error, e.what());
        return;
    }

}
void RecordCRUDApi::get_record_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) {   
    // Getting the path params
    auto realmId = request.param(":realmId").as<std::string>();
    auto storageId = request.param(":storageId").as<std::string>();
    auto recordId = request.param(":recordId").as<std::string>();
    
    Logger::udsf_server().info("--GET!--/%s/%s/records/%s",realmId.c_str(),storageId.c_str(),recordId.c_str());
    // Getting the query params
    auto supportedFeaturesQuery = request.query().get("supported-features");
    Pistache::Optional<std::string> supportedFeatures;
    if(!supportedFeaturesQuery.isEmpty()){
        std::string valueQuery_instance;
        if(fromStringValue(supportedFeaturesQuery.get(), valueQuery_instance)){
            supportedFeatures = Pistache::Some(valueQuery_instance);
        }
    }
    
    // Getting the header params
    auto ifNoneMatch = request.headers().tryGetRaw("If-None-Match");
    auto ifModifiedSince = request.headers().tryGetRaw("If-Modified-Since");

    try {
      this->get_record(realmId, storageId, recordId, ifNoneMatch, ifModifiedSince, supportedFeatures, response);
    } catch (nlohmann::detail::exception &e) {
        //send a 400 error
        response.send(Pistache::Http::Code::Bad_Request, e.what());
        return;
    } catch (Pistache::Http::HttpError &e) {
        response.send(static_cast<Pistache::Http::Code>(e.code()), e.what());
        return;
    } catch (std::exception &e) {
        //send a 500 error
        response.send(Pistache::Http::Code::Internal_Server_Error, e.what());
        return;
    }

}
void RecordCRUDApi::search_record_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) {
    // Getting the path params
    auto realmId = request.param(":realmId").as<std::string>();
    auto storageId = request.param(":storageId").as<std::string>();
    
    // Getting the query params
    auto limitRangeQuery = request.query().get("limit-range");
    Pistache::Optional<int32_t> limitRange;
    if(!limitRangeQuery.isEmpty()){
        int32_t valueQuery_instance;
        if(fromStringValue(limitRangeQuery.get(), valueQuery_instance)){
            limitRange = Pistache::Some(valueQuery_instance);
        }
    }
    auto filterQuery = request.query().get("filter");
    Pistache::Optional<SearchExpression> filter;
    if(!filterQuery.isEmpty()){
        SearchExpression valueQuery_instance;
       // if(fromStringValue(filterQuery.get(), valueQuery_instance)){
           // filter = Pistache::Some(valueQuery_instance);
       // }
    }
    auto countIndicatorQuery = request.query().get("count-indicator");
    Pistache::Optional<bool> countIndicator;
    if(!countIndicatorQuery.isEmpty()){
        bool valueQuery_instance;
        if(fromStringValue(countIndicatorQuery.get(), valueQuery_instance)){
            countIndicator = Pistache::Some(valueQuery_instance);
        }
    }
    auto supportedFeaturesQuery = request.query().get("supported-features");
    Pistache::Optional<std::string> supportedFeatures;
    if(!supportedFeaturesQuery.isEmpty()){
        std::string valueQuery_instance;
        if(fromStringValue(supportedFeaturesQuery.get(), valueQuery_instance)){
            supportedFeatures = Pistache::Some(valueQuery_instance);
        }
    }
    
    try {
      this->search_record(realmId, storageId, limitRange, filter, countIndicator, supportedFeatures, response);
    } catch (nlohmann::detail::exception &e) {
        //send a 400 error
        response.send(Pistache::Http::Code::Bad_Request, e.what());
        return;
    } catch (Pistache::Http::HttpError &e) {
        response.send(static_cast<Pistache::Http::Code>(e.code()), e.what());
        return;
    } catch (std::exception &e) {
        //send a 500 error
        response.send(Pistache::Http::Code::Internal_Server_Error, e.what());
        return;
    }

}
void RecordCRUDApi::update_meta_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) {
    // Getting the path params
    auto realmId = request.param(":realmId").as<std::string>();
    auto storageId = request.param(":storageId").as<std::string>();
    auto recordId = request.param(":recordId").as<std::string>();
    
    // Getting the body param
    std::vector<PatchItem> patchItem;
    
    // Getting the query params
    auto supportedFeaturesQuery = request.query().get("supported-features");
    Pistache::Optional<std::string> supportedFeatures;
    if(!supportedFeaturesQuery.isEmpty()){
        std::string valueQuery_instance;
        if(fromStringValue(supportedFeaturesQuery.get(), valueQuery_instance)){
            supportedFeatures = Pistache::Some(valueQuery_instance);
        }
    }
    
    // Getting the header params
    auto ifMatch = request.headers().tryGetRaw("If-Match");

    try {
      nlohmann::json::parse(request.body()).get_to(patchItem);
      this->update_meta(realmId, storageId, recordId, patchItem, ifMatch, supportedFeatures, response);
    } catch (nlohmann::detail::exception &e) {
        //send a 400 error
        response.send(Pistache::Http::Code::Bad_Request, e.what());
        return;
    } catch (Pistache::Http::HttpError &e) {
        response.send(static_cast<Pistache::Http::Code>(e.code()), e.what());
        return;
    } catch (std::exception &e) {
        //send a 500 error
        response.send(Pistache::Http::Code::Internal_Server_Error, e.what());
        return;
    }

}

void RecordCRUDApi::record_crud_api_default_handler(const Pistache::Rest::Request &, Pistache::Http::ResponseWriter response) {
    Logger::udsf_server().debug("record_crud_api_default_handler sreceive message");
    response.send(Pistache::Http::Code::Not_Found, "The requested method does not exist");
}

}
}
}
}

