#include <gtest/gtest.h>
#include "PrintTo_Qt.h"

#include "catalog/PgClass.h"
#include "catalog/PgDatabaseCatalog.h"
#include "ui/catalog/tables/TableTreeBuilder.h"
#include "ui/catalog/tables/TableNode.h"
#include "catalog/PgInheritsContainer.h"

TEST(TableTreeBuilder, EmptySourceEmptyResult)
{
    std::map<Oid, PgClass> source;
    PgDatabaseCatalog catalog;
    PgInheritsContainer inherited(catalog);
    TableTreeBuilder builder(source, inherited);
    auto [result, index] = builder.Build();

    EXPECT_EQ(result->children.size(), 0);
}


TEST(TableTreeBuilder, TopLevelOnly)
{
    std::map<Oid, PgClass> source;

    PgDatabaseCatalog catalog;
    PgClass cls1(catalog, 1000, "a", 11);
    source.emplace(1000, cls1);
    PgInheritsContainer inherited(catalog);
    TableTreeBuilder builder(source, inherited);
    auto [result, index] = builder.Build();

    EXPECT_EQ(result->children.size(), 1);
}

class FakeIFindParents : public IFindParents
{
public:
    std::vector<Oid> getParentsOf(Oid oid) const override
    {
        if (oid == 1001)
            return { 1002 };
        return {};
    }
};

TEST(TableTreeBuilder, WithChild)
{
    std::map<Oid, PgClass> source;

    FakeIFindParents findParents;
    PgDatabaseCatalog catalog;
    PgClass cls1(catalog, 1001, "a", 11);
    source.emplace(1001, cls1);
    PgClass cls2(catalog, 1002, "b", 11);
    source.emplace(1002, cls2);
    PgInheritsContainer inherited(catalog);
    TableTreeBuilder builder(source, findParents);
    auto [result, index] = builder.Build();

    EXPECT_EQ(result->children.size(), 1);
    EXPECT_EQ(result->children[0]->children.size(), 1);
    EXPECT_TRUE(result->children[0]->children[0]->parent.lock() == result->children[0]);
}
