#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());
}
