#include "archive.h"
#include "config.h"
#include "manager.h"
#include "globals.h"

#include <library/cpp/logger/global/global.h>

bool TRTYFastArchiveManager::GetDocInfo(const ui32 docId, NJson::TJsonValue& result) const {
    auto doc = GetDoc(docId);
    if (!doc)
        return false;

    for (ui32 i = 0; i < doc->GetPropertiesCount(); ++i) {
        NJson::TJsonValue jsonValues(NJson::JSON_ARRAY);
        TStringBuf name = doc->GetPropertyName(i);
        const auto& values = doc->GetPropertyValues(i);
        for (const TStringBuf& value : values)
            jsonValues.AppendValue(value);

        result.InsertValue(name, jsonValues);
    }

    return true;
}

ui32 TRTYFastArchiveManager::GetDocumentsCount() const {
    return GetArchive().Docs.size();
}

const IFastArchiveDoc* TRTYFastArchiveManager::GetDoc(ui32 docId) const {
    if (Y_UNLIKELY(docId >= GetDocumentsCount()))
        return nullptr;

    const TFastArchiveDoc* doc = &GetArchive().Docs[docId];
    Y_ASSERT(!doc || doc->GetDocId() == docId);
    return doc;
}

TRTYFastArchiveDiskManager::TRTYFastArchiveDiskManager(const TString& file)
    : ArchiveFile(file)
{}

bool TRTYFastArchiveDiskManager::DoOpen() {
    if (!NFs::Exists(ArchiveFile))
        return false;

    TIFStream input(ArchiveFile);

    ui32 version;
    if (!ReadArchiveHeader(input, version, Properties) || version != FastArchiveVersion)
        return false;

    TFastArchiveIterator iterator(input, Pool);
    for (; iterator.Valid(); iterator.Next()) {
        const TFastArchiveDoc& doc = iterator.GetDoc();
        const ui32 docId = doc.GetDocId();
        if (Docs.size() < docId + 1)
            Docs.resize(docId + 1);

        Docs[docId] = doc;
    }

    Pool.Finalize();

    return true;
}

bool TRTYFastArchiveDiskManager::DoClose() {
    Docs.clear();
    Pool.Clear();
    return true;
}

bool TRTYFastArchiveMemoryManager::HasProperty(const TStringBuf& name) const {
    return Config.GetFastProperties().contains(name);
}
