#include "PdfDocumentCatalog.h"

#include "PdfOutline.h"
#include "PdfPageTree.h"
#include "PdfPage.h"
#include "PdfXRefTable.h"

PdfDocumentCatalog::PdfDocumentCatalog()
    : PdfObject()
{
    mOutlines = std::make_unique<PdfOutlineCollection>();
    mPages = std::make_unique<PdfPageTree>();
}

unsigned PdfDocumentCatalog::indexObjects(unsigned count)
{
    auto newCount = count + 1;
    mObjectNumber = newCount;
    auto objectCount = mOutlines->indexObjects(mObjectNumber);
    objectCount = mPages->indexObjects(objectCount);
    return objectCount;
}

std::string PdfDocumentCatalog::toString(PdfXRefTable* xRefTable)
{
    updateDictionary();
    auto content = getStringPrefix();
    content += mDictionary.toString();
    content += getStringSuffix();
    xRefTable->addRecord(content.size(), mGenerationNumber, mIsFree);

    content += mOutlines->toString(xRefTable);

    content += mPages->toString(xRefTable);

    return content;
}

void PdfDocumentCatalog::updateDictionary()
{
    mDictionary.addStringItem("Type", "/Catalog");
    mDictionary.addStringItem("Outlines", mOutlines->getRefString());
    mDictionary.addStringItem("Pages", mPages->getRefString());
}
