#include "../categories.h"
#include "../magic_strings.h"
#include "../attribute_dumper.h"
#include "../relation_dumper.h"

namespace maps {

namespace {
const std::string EDGE_ID = "edge_id";
const std::string F_ZLEV = "f_zlev";
const std::string T_ZLEV = "t_zlev";
const std::string F_NODE_ID = "f_node_id";
const std::string T_NODE_ID = "t_node_id";
} // namespace

struct AdElCategory: public Category {
    std::string name() const override
    {
        return category::AD_EL;
    }

    const Table& table() const override
    {
        return table::EDGE;
    }

    std::string loadIdsSql() const override
    {
        return "SELECT DISTINCT face_edge.edge_id FROM ad_face, face_edge "
            "WHERE (face_edge.face_id = ad_face.face_id)";
    }

    std::string loadRowsSqlTemplate() const override
    {
        return "SELECT " + EDGE_ID + " " + ID + ", "
            + "st_asgeojson(shape) " + SHAPE + ", "
            + F_ZLEV + ", "
            + T_ZLEV + ", "
            + F_NODE_ID + ", "
            + T_NODE_ID + " FROM edge WHERE edge_id in %1%";
    }

    void tupleToJson(
        json::ObjectBuilder& builder,
        const pqxx::row& tuple) const override
    {
        builder[jkey::ATTRIBUTES] = [&](json::ObjectBuilder builder) {
            AttributeDumper ad(name(), builder);
            ad.dumpCategory();
            ad.dump<int>(F_ZLEV, tuple);
            ad.dump<int>(T_ZLEV, tuple);
        };
        dumpGeometry(builder, tuple);
        builder[jkey::RELATIONS] = [&](json::ArrayBuilder builder) {
            RelationDumper rd(builder, tuple);
            rd.dump(relation::AD_EL_START, F_NODE_ID);
            rd.dump(relation::AD_EL_END, T_NODE_ID);
        };
    }
};

DEFINE_CATEGORY_OBJECT(AdEl, AD_EL);

} // namespace maps
