#include "pyvalidator.h"

#include <yandex/maps/wiki/common/pyutils.hpp>
#include <yandex/maps/pylogger/helpers.h>
#include <maps/libs/geolib/include/serialization.h>

#include <boost/lexical_cast.hpp>

namespace maps {
namespace wiki {
namespace validator {
namespace python {

PyValidator::PyValidator(const ValidatorConfig& validatorConfig)
    : validator_(validatorConfig)
{
}

ResultPtr PyValidator::run(
    const bp::object& checks,
    pgpool3::Pool& pgPool,
    revision::DBID branchId,
    revision::DBID commitId,
    const bp::object& aoiWkb,
    const bp::object& aoiCoverageDir,
    const bp::object& aoiBuffer)
{
    auto checksVec = common::toVector<TCheckId>(checks);

    static const auto none = bp::object();
    if (aoiWkb != none) {
        REQUIRE(aoiCoverageDir != none, "No AOI coverage directory");
        REQUIRE(!aoiBuffer.is_none(), "No AOI buffer");

        maps::pylogger::PyThreadSaver ts;
        std::stringstream aoiBuf((bp::extract<std::string>(aoiWkb)()));
        auto aoiGeom = geolib3::WKB::read<geolib3::Polygon2>(aoiBuf);
        auto coverageDir = bp::extract<std::string>(aoiCoverageDir)();
        auto buffer = bp::extract<double>(aoiBuffer)();

        return validator_.run(checksVec, pgPool, branchId, commitId,
            std::move(aoiGeom), std::move(coverageDir), buffer);
    } else {
        maps::pylogger::PyThreadSaver ts;
        return validator_.run(checksVec, pgPool, branchId, commitId);
    }
}

void PyValidator::enableCardinalityCheck()
{
    validator_.enableCardinalityCheck();
}

void PyValidator::initModules()
{
    validator_.initModules();
}

bp::list PyValidator::modules() const
{ return common::toPyList(validator_.modules()); }

} // namespace python
} // namespace validator
} // namespace wiki
} // namespace maps
