#include "dataset_maker.h"

#include <maps/libs/log8/include/log8.h>
#include <maps/libs/common/include/exception.h>

namespace maps::wiki::exporter {

DatasetMaker::DatasetMaker(
        const ExportConfig& exportCfg,
        const ExportFiles& exportFiles)
    : exportCfg_(exportCfg)
    , exportFiles_(exportFiles)
    , fail_(false)
    , pool_(1)
{}

void DatasetMaker::make(const Region& region)
{
    REQUIRE(!fail_, "Dataset maker is already broken");

    bool pushed = pool_.push([this, region] { safeMake(region); });
    REQUIRE(pushed, "Dataset maker can not execute threaded task");
}

void DatasetMaker::cancel()
{
    fail_ = true;
}

Datasets DatasetMaker::datasets()
{
    pool_.shutdown();
    REQUIRE(!fail_, "Dataset maker is not valid");
    return std::move(datasets_);
}

void DatasetMaker::safeMake(const Region& region)
{
    if (fail_) {
        return;
    }

    try {
        auto regionDataset = makeDataset(exportCfg_, exportFiles_, region);
        if (!fail_ && regionDataset) {
            datasets_.emplace_back(std::move(*regionDataset));
        }
    } catch (const maps::Exception& ex) {
        fail_ = true;
        ERROR() << "Dataset maker, error: " << ex;
    } catch (const std::exception& ex) {
        fail_ = true;
        ERROR() << "Dataset maker, error: " << ex.what();
    } catch (...) {
        fail_ = true;
        ERROR() << "Dataset maker, unknown error";
    }
}

} // namespace maps::wiki::exporter
