#include "configuration.h"
#include "yacare_params.h"

#include <maps/libs/chrono/include/time_point.h>

#include <maps/infra/yacare/include/yacare.h>
#include <maps/infra/yacare/include/error.h>


namespace maps::mrc::browser {

YCR_PANIC_IF(!Configuration::instance()->areAllDatasetsInTargetState(),
        "datasets-not-in-target-state", "Some of the datasets are not in target state");

YCR_PANIC_IF(!Configuration::instance()->areAllDatasetsLoaded(),
        "datasets-loaded", "Some of the datasets are not loaded");

YCR_PANIC_IF(!Configuration::instance()->areCartographDesignsLoaded(),
    "designs-loaded", "Some of cartograph designs are not loaded");

YCR_RESPOND_TO("POST /service/reload_dataset", dataset, YCR_RESTRICT_TO_LOCAL)
{
    std::optional<std::string> maybePath = request.optParam("path");

    if (maybePath.has_value() && maybePath.value().empty()) {
        maybePath = std::nullopt;
    }

    INFO() << "Processing request to reload dataset '" << dataset << "' from path '"
        << (maybePath.has_value() ? maybePath.value() : "<none>");

    size_t gracePeriod = yacare::config()->shutdown().grace_period();
    INFO() << "Grace period is " << gracePeriod << " secs";
    auto timeToSwitchDataset = std::chrono::steady_clock::now() + std::chrono::seconds(gracePeriod);

    if (dataset == ROAD_GRAPH_DATASET_NAME) {
        Configuration::instance()->setRoadGraphDatasetTargetPath(maybePath, timeToSwitchDataset);
    } else if (dataset == PEDESTRIAN_GRAPH_DATASET_NAME) {
        Configuration::instance()->setPedestrianGraphDatasetTargetPath(maybePath, timeToSwitchDataset);
    } else if (dataset == ROAD_PHOTO_TO_EDGE_DATASET_NAME) {
        Configuration::instance()->setRoadPhotoToEdgeDatasetTargetPath(maybePath, timeToSwitchDataset);
    } else if (dataset == PEDESTRIAN_PHOTO_TO_EDGE_DATASET_NAME) {
        Configuration::instance()->setPedestrianPhotoToEdgeDatasetTargetPath(maybePath, timeToSwitchDataset);
    } else if(dataset == REGION_PRIVACY_DATASET_NAME) {
        Configuration::instance()->setRegionPrivacyDatasetTargetPath(maybePath, timeToSwitchDataset);
    } else if (dataset == MRC_DATASET_NAME) {
        Configuration::instance()->setDataAccessDatasetTargetPath(maybePath, timeToSwitchDataset);
    } else {
        throw yacare::errors::BadRequest() << "Unknown dataset '" << dataset << "'";
    }
}

YCR_RESPOND_TO("POST /service/reload_design", YCR_RESTRICT_TO_LOCAL)
{
    Configuration::instance()->reloadDesign();
}

} // namespace maps::mrc::browser
