#include "dump.h"

#include <library/cpp/testing/unittest/registar.h>

#include <robot/jupiter/library/rtdoc/file/reader.h>
#include <robot/jupiter/library/rtdoc/file/writer.h>

#include <util/system/fs.h>

using namespace NRtDoc;

class TRtDocDumpToolTest: public NUnitTest::TTestBase {
    UNIT_TEST_SUITE(TRtDocDumpToolTest)
        UNIT_TEST(TestDump);
    UNIT_TEST_SUITE_END();

    void Cleanup() {
        if (NFs::Exists("index_1")) {
            NFs::RemoveRecursive("index_1");
        }
    }

    void SetUp() override {
        Cleanup();
        TFsPath("index_1").MkDir();
    }

    void TearDown() override {
        Cleanup();
    }

    void Write(TPrepWriter& wr, ui32 tmpDocId, NJupiter::TMercuryLumps& row) {
        TBuffer buf;
        buf.Resize(row.ByteSize());
        Y_VERIFY(row.SerializeToArray(buf.Data(), buf.Size()));
        wr.AddData(tmpDocId, TBlob::FromBufferSingleThreaded(buf));
    }

    void WriteTestData(TPrepWriter& wr) {
        ui32 tmpDocId = 2;
        NJupiter::TMercuryLumps row;
        NJupiter::TMapType* cell;

        row.Clear();
        cell = row.AddLumps();
        cell->SetName("A");
        cell->SetData("0");
        cell = row.AddLumps();
        cell->SetName("B");
        cell->SetData("1");
        Write(wr, tmpDocId++, row);

        row.Clear();
        cell = row.AddLumps();
        cell->SetName("B");
        cell->SetData("20");
        cell = row.AddLumps();
        cell->SetName("B");
        cell->SetData("22");
        Write(wr, tmpDocId++, row);

        row.Clear();
        Write(wr, tmpDocId++, row);

        row.Clear();
        Write(wr, tmpDocId++, row);

        TDocIdMap m;
        m.SetIdMap(tmpDocId);
        m.MutableData()->at(tmpDocId - 2) = TDocIdMap::DeletedDocument();

        wr.WriteDocIdMap(&m);
    }

    void TestDump() {
        TFsPath prepFile = "index_1/prep.lumps";

        {
            TPrepWriter wr(prepFile);
            WriteTestData(wr);
            wr.Finish();
        }

        TStringStream ss;
        TRtDocDumper dumper;
        dumper.SetLevel(EDumpLevel::Row);
        dumper.SetNoPretty(true);
        dumper.Start(ss);

        TPrepTable actualTbl(prepFile);
        actualTbl.Init();
        for (IPrepIterator::TPtr item = actualTbl.Open(); item->Next();) {
            dumper.Dump(*item);
        }
        dumper.Finish();
        ss.Flush();

        UNIT_ASSERT_VALUES_EQUAL("[{\"DocId\":0},{\"DocId\":1},{\"DocId\":2,\"A\":\"0\",\"B\":\"1\"},{\"DocId\":3,\"B\":[\"20\",\"22\"]},{\"DocId\":5}]", ss.Str());
    }
};

UNIT_TEST_SUITE_REGISTRATION(TRtDocDumpToolTest);
