#pragma once

#include <saas/rtyserver/index_storage/index_storage.h>
#include <saas/rtyserver/indexer_disk/indexer.h>
#include <saas/rtyserver/merger/index_merger.h>

#include <saas/protos/rtyserver.pb.h>

#include <util/generic/ptr.h>

struct TRTYServerConfig;
struct TDaemonModulesRunner;

struct TParseResult {
    TString ErrorMessage;
    THolder<TParsedDocument> Document;

    TParseResult(const TString& errorMessage)
        : ErrorMessage(errorMessage)
        , Document(nullptr)
        {
    }
    TParseResult(THolder<TParsedDocument>&& document)
        : ErrorMessage()
        , Document(std::move(document))
        {
    }
};

struct TIndexResult {
    TString ErrorMessage;
    bool IndexSuccess;

    TIndexResult(const TString& errorMessage)
        : ErrorMessage(errorMessage)
        , IndexSuccess(false)
        {
    }
    TIndexResult(bool success)
        : IndexSuccess(success)
        {
    }

    operator bool() const {
        return IndexSuccess;
    }
};

class TStandaloneIndexer {
public:
    TStandaloneIndexer(const TString& textOfRTYServerConfig, const THashMap<TString, TString>& configVariables = {}, bool runModules = false);
    ~TStandaloneIndexer();

    void EnableIndexing();
    void DisableIndexing();
    bool IndexingEnabled() const;
    TIndexResult Index(TParsedDocument& document);
    TIndexResult Index(const NRTYServer::TMessage::TDocument &msgDoc);
    void IndexUnsafe(TParsedDocument& document);
    void IndexUnsafe(const NRTYServer::TMessage::TDocument &msgDoc);
    void RemoveDoc(const TParsedDocument& document);
    TParseResult GetParsedDocument(const NRTYServer::TMessage::TDocument &msgDoc, const NRTYServer::TDocParseContext& c) const;
    const TString& GetIndexerDir() const;

    void EnableMerging();
    void DisableMerging();
    bool MergingEnabled() const;
    TVector<TString> GetSegmentsForMerge();
    void Merge();
    void MergeTo(TVector<TString> sourceSegments, TString destDirectory, TString destSegment);

private:
    THolder<TRTYServerConfig> Config;
    THolder<TDaemonModulesRunner> Modules;
    TIndexStorage::TPtr IndexStorage;
    THolder<TIndexer> Indexer;
    THolder<TIndexMerger> Merger;
};
