#pragma once

#include <saas/protos/rtyserver.pb.h>
#include <yweb/protos/indexeddoc.pb.h>
#include <google/protobuf/text_format.h>
#include <util/stream/file.h>
#include <util/generic/maybe.h>
#include <util/generic/yexception.h>
#include <util/folder/path.h>

class TIndDocOutput {
public:
    struct TOptions {
        TString OutputDir;
        TString FilePrefix;
        i32 NumBegin = 1;
        i32 NumEnd = Max<int>();
    };

private:
    TOptions Opts;
    const TFsPath OutputDir;

    i32 CurNo = -1;

public:
    TIndDocOutput(const TOptions options)
        : Opts(options)
        , OutputDir(options.OutputDir)
    {
        if (!Opts.FilePrefix)
            Opts.FilePrefix = "inddoc.";
        Y_ENSURE(Opts.NumBegin <= Opts.NumEnd);
    }

    void Reset() {
        CurNo = -1;
    }

    TMaybe<TString> NextFile() {
        if (CurNo == -1)
            CurNo = Opts.NumBegin;
        if (CurNo > Opts.NumEnd)
            return TMaybe<TString>();
        return TString(OutputDir / (Opts.FilePrefix + ToString(CurNo++)));
    }

    void Write(const TString& fileName, const NRTYServer::TMessage::TDocument& doc) {
        Y_ENSURE_EX(doc.HasIndexedDoc(), yexception() << "missing IndexingDoc");
        Write(fileName, doc.GetIndexedDoc());
    }

    void Write(const TString& fileName, const NRealTime::TIndexedDoc& doc) {
        TString hr;
        Y_ENSURE(google::protobuf::TextFormat::PrintToString(doc, &hr));
        TUnbufferedFileOutput file(fileName);
        file << hr;
        file.Flush();
    };
};
