#include <maps/wikimap/mapspro/services/tasks_feedback/src/import_feedback_worker/lib/worker.h>

#include <maps/libs/cmdline/include/cmdline.h>
#include <maps/tools/grinder/worker/include/api.h>
#include <maps/libs/log8/include/log8.h>
#include <maps/libs/mongo/include/init.h>
#include <yandex/maps/wiki/common/default_config.h>
#include <yandex/maps/wiki/common/extended_xml_doc.h>

#include <memory>

namespace worker = maps::grinder::worker;
namespace import_fb = maps::wiki::import_feedback;

namespace {

constexpr size_t WORKER_CONCURRENCY = 1;

} // anonymous namespace


int main(int argc, char* argv[]) try
{
    maps::cmdline::Parser parser;
    auto workerConfig = parser.string("config")
            .help("path to worker configuration");
    auto syslogTag = parser.string("syslog-tag")
            .help("redirect log output to syslog with given tag");
    auto grinderConfig = parser.string("grinder-config")
            .help("path to grinder configuration file");

    parser.parse(argc, argv);

    if (syslogTag.defined()) {
        maps::log8::setBackend(maps::log8::toSyslog(syslogTag));
    }

    maps::mongo::init();

    std::unique_ptr<maps::wiki::common::ExtendedXmlDoc> configXml;
    if (workerConfig.defined()) {
        configXml.reset(new maps::wiki::common::ExtendedXmlDoc(workerConfig));
    } else {
        configXml = maps::wiki::common::loadDefaultConfig();
    }

    worker::Options workerOpts;

    if (grinderConfig.defined()) {
        workerOpts.setConfigLocation(grinderConfig);
    }

    import_fb::Worker worker(std::move(configXml));

    INFO() << "feedback-import-worker started";

    workerOpts.on("import_feedback",
        [&](const worker::Task& task) {
            worker.doTask(task);
        }
    ).setConcurrencyLevel(WORKER_CONCURRENCY);

    worker::run(std::move(workerOpts));

    return EXIT_SUCCESS;
} catch (const maps::Exception& e) {
    FATAL() << "Worker failed: " << e;
    return EXIT_FAILURE;
} catch (const std::exception& e) {
    FATAL() << "Worker failed: " << e.what();
    return EXIT_FAILURE;
}
