#include "document_builder.h"

#include <saas/api/action.h>
#include <library/cpp/json/json_reader.h>
#include <util/folder/path.h>
#include <util/stream/file.h>

IFileDocumentBuilder::IFileDocumentBuilder(const TString& dirname, const TString& suffix)
    : Dirname(dirname)
{
    FileList.Fill(Dirname, TStringBuf(), TStringBuf(suffix), 1, true);
}

bool IFileDocumentBuilder::GetNext(NRTYServer::TMessage::TDocument& document) {
    const char* filename = FileList.Next();
    if (filename == nullptr)
        return false;
    TFsPath filepath(Dirname);
    filepath /= filename;
    ReadFile(filepath, document);
    return true;
}

void TActionFileDocumentBuilder::ReadFile(const TString& filepath, NRTYServer::TMessage::TDocument& document) {
    TUnbufferedFileInput input(filepath);
    NJson::TJsonValue json;
    NJson::ReadJsonTree(&input, true, &json);
    NSaas::TAction action;
    action.ParseFromJson(json);
    document.Clear();
    document.CopyFrom(action.ToProtobuf().GetDocument());
}

void TMsgDocFileDocumentBuilder::ReadFile(const TString& filepath, NRTYServer::TMessage::TDocument& document) {
    TUnbufferedFileInput input(filepath);
    document.Clear();
    document.ParseFromArcadiaStream(&input);
}
