#include "connector.h"

#include <maps/wikimap/mapspro/libs/masstransit/masstransit.h>

namespace maps::wiki::masstransit {

YmapsdfConnectorHandler::YmapsdfConnectorHandler(Masstransit& masstransit)
    : YmapsdfObjectHandler(masstransit, masstransit.connectors)
{ }

std::vector<FtType>
YmapsdfConnectorHandler::ftTypes() const
{
    return {
        FtType::TransportBusThreadConnector,
        FtType::TransportTramThreadConnector,
        FtType::TransportWaterwayThreadConnector,
        FtType::TransportMetroThreadConnector
    };
}

StringVector
YmapsdfConnectorHandler::attrs() const
{
    return {attr::IS_PREDICTABLE};
}

StringVector
YmapsdfConnectorHandler::rolesToSlaves() const
{
    return {role::SRC_THREAD, role::DST_THREAD};
}

void
YmapsdfConnectorHandler::addObject(const pqxx::row& tuple)
{
    auto connector = std::make_shared<Connector>();

    const auto connectorId = getAttr<DBID>(tuple, ymapsdf::ID);

    connector->connectorId = connectorId;
    connector->srcThreadId = getAttr<DBID>(tuple, role::SRC_THREAD);
    connector->dstThreadId = getAttr<DBID>(tuple, role::DST_THREAD);
    connector->ftType = getAttr<FtType>(tuple, ymapsdf::FT_TYPE_ID);
    connector->isPredictable = getAttr<bool>(tuple, attr::IS_PREDICTABLE, false);

    auto mtrId =
        std::to_string(connector->srcThreadId) +
        "_" +
        std::to_string(connector->dstThreadId) +
        "_" +
        std::to_string(connector->connectorId);

    idMap().add(connectorId, mtrId, MtrType::Connector);
    insert(connectorId, connector);
}

MtrConnectorHandler::MtrConnectorHandler(Masstransit& masstransit)
    : MtrObjectHandler(masstransit, masstransit.connectors)
{ }

void
MtrConnectorHandler::writeObject(StreamMap& ostreams, const Object& object)
{
    const auto& connector = dynamic_cast<const Connector&>(object);
    auto& ostream = ostreams[fileNames().front()];

    ostream
        << idMap().getMtrId(connector.connectorId) << FIELD_SEPARATOR
        << idMap().getMtrId(connector.srcThreadId) << FIELD_SEPARATOR
        << idMap().getMtrId(connector.dstThreadId) << FIELD_SEPARATOR
        << connector.isPredictable << std::endl;
}

} // namespace maps::wiki::masstransit
