#pragma once

#include "const.h"
#include "manager.h"
#include <robot/jupiter/library/rtdoc/file/model/interfaces.h>

#include <saas/rtyserver/indexer_core/abstract_model.h>
#include <saas/rtyserver_jupi/library/rtyt/config.pb.h>
#include <saas/library/rtyt/lib/client.h>
#include <util/system/mutex.h>

class TBaseGeneratorBuilder;

namespace NRTYServer {

class TJupiBuilder : public IIndexComponentBuilder {
private:
    using TWriterPtr = THolder<NRtDoc::IPrepWriter>;

private:
    TMutex Mutex;
    TMutex RtytMutex;
    TWriterPtr Writer;

    const TString Prefix;
    const TString CypressPrefix;
    TJupiComponentManager* Manager;

    bool RtytEnabled = false;
    TIntrusivePtr<NRTYT::TClientBase> RtytClient;
    THashMap<TString, const NProtoBuf::Descriptor*> PrepTypes;
    THashMap<TString, TIntrusivePtr<NYT::TTableWriter<::google::protobuf::Message>>> RtytWriters;
    NFusion::TRTYTBuilderConfig RtytConfig;

public:
    TJupiBuilder(const TString& indexFilesPrefix, bool rtytEnabled, NFusion::TRTYTBuilderConfig config);

private:
    void CreateWriter();
    void InitializeRTYT();
    static void WriteIndexFrq(const TString& path, const NRtDoc::TDocIdMap* map, const THashSet<ui32>& deletedDocids);

public:
    virtual void Index(int threadId, const TParsedDocument& document, const ui32 docId) override;

    virtual bool DoClose(const NRTYServer::TBuilderCloseContext& context) override;

    virtual void DoDiscard() override;

    virtual bool Start() override {
        return true;
    }

    virtual bool Stop() override {
        return true;
    }

    virtual void InitInteractions(const NRTYServer::IIndexBuildersStorage& /*storage*/) override {
    }

    virtual NRTYServer::IIndexComponentManager* GetManager() override {
        return Manager;
    }

};

}
