#include <Poco/Data/MySQL/Connector.h>

#include <wmconsole/legacy/util/database/database_holder.h>
#include <wmconsole/legacy/util/database/multi_select.h>
#include <wmconsole/legacy/util/logger.h>
#include <wmconsole/legacy/util/thr_apps/close_event.h>

#include "host_processor.h"
#include "main.h"
#include "mirrors_resolver.h"
#include "xml_holder.h"

Poco::Logger &logger() {
    static Poco::Logger &instance(Poco::Logger::get("XmlLimits"));
    return instance;
}

namespace NWebmaster {

const std::string TApplication::OP_XML_DB_URLS = "xml-db-urls";
const std::string TApplication::OP_XML_LIMITS_TABLE = "xml-limits-table";
const std::string TApplication::OP_YT_CLUSTER = "yt-cluster";
const std::string TApplication::OP_YT_ROOT = "yt-root";

int TApplication::doMain(const std::vector<std::string> & /*args*/) {
    try {
        print_keys();

        Poco::Data::MySQL::Connector::registerConnector();
        TDatabaseHolder::instance().init(getUserDbUrl(), getHostDbUrls());
        TXmlHolder::instance().init(getUserDbUrl(), getXmlDbUrls());

        std::deque<std::string> hosts;
        WMCSession::Ptr session =  TDatabaseHolder::instance().session();
        //queries::get_all_verified_hosts(session->getUserSession(), hosts, t_close_event::instance());
        queries::select(session->getUserSession(), "SELECT lcase(name) FROM (SELECT DISTINCT host_id FROM tbl_xmllimit_delegations) tbl_ NATURAL JOIN tbl_hosts", hosts, t_close_event::instance());

        log_info << config().getString(OP_YT_ROOT);

        TMirrorResolver::Ptr resolver(new TMirrorResolver(hosts));

        THostProcessor(
            config().getString(OP_YT_CLUSTER),
            config().getString(OP_YT_ROOT),
            config().getString(OP_XML_LIMITS_TABLE),
            resolver
        );

        return Application::EXIT_OK;
    } catch (Poco::Exception &e) {
        log_error << "Poco::Exception " << e.message();
        return Application::EXIT_SOFTWARE;
    } catch (std::exception &e) {
        log_error << "std::exception " << e.what();
        return Application::EXIT_SOFTWARE;
    } catch ( ... ) {
        log_error << "Unknown processing error!";
        return Application::EXIT_SOFTWARE;
    }
}

} //namespace NWebmaster

POCO_APP_MAIN(NWebmaster::TApplication)
