#pragma once

#include "archive.h"

#include <saas/rtyserver/indexer_core/indexer_core.h>

class TParsedDocument;
class TRTYFastArchiveConfig;

class TRTYFastArchiveBuilder: public NRTYServer::IIndexComponentBuilder {
public: // NRTYServer::IIndexComponentBuilder
    TRTYFastArchiveBuilder(const TString& componentName)
        : NRTYServer::IIndexComponentBuilder(componentName)
    {

    }
    void Index(int threadID, const TParsedDocument& document, const ui32 docId) override;
    bool Start() override { return true; }
    bool Stop() override { return true; }
    void InitInteractions(const NRTYServer::IIndexBuildersStorage& /*storage*/) override {}

public:
    virtual void DoStoreDocument(int threadId, ui32 docId, const TFastArchiveDoc& buffer) = 0;
    virtual TFastArchiveStringPool& GetStringPool() = 0;

    void Index(ui32 docId, TFastArchiveDoc& doc, int threadId = 0);

protected:
    TMutex PoolLock;
};

class TRTYFastArchiveDiskBuilder: public TRTYFastArchiveBuilder {
public:
    TRTYFastArchiveDiskBuilder(const NRTYServer::TIndexerConfig& indexerConfig,
                               const TRTYFastArchiveConfig& componentConfig, const TString& indexDir,
                               const TString& componentName
        );

public: // TRTYFastArchiveBuilder
    NRTYServer::IIndexComponentManager* GetManager() override { return nullptr; }
    bool DoClose(const NRTYServer::TBuilderCloseContext& context) override;
    void DoStoreDocument(int threadId, ui32 docId, const TFastArchiveDoc& buffer) override;
    TFastArchiveStringPool& GetStringPool() override;

private:
    const NRTYServer::TIndexerConfig& IndexerConfig;
    const TRTYFastArchiveConfig& ComponentConfig;
    const TString IndexDir;

    TVector<TSimpleSharedPtr<TOFStream>> ArchiveFile;
    TFastArchiveStringPool StringPool;
};

class TRTYFastArchiveMemoryBuilder: public TRTYFastArchiveBuilder {
public:
    TRTYFastArchiveMemoryBuilder(const NRTYServer::TIndexerConfig& indexerConfig,
                                 const TRTYFastArchiveConfig& componentConfig, const TString& componentName);

public:
    NRTYServer::IIndexComponentManager* GetManager() override;
    bool DoClose(const NRTYServer::TBuilderCloseContext& context) override;
    void DoStoreDocument(int threadId, ui32 docId, const TFastArchiveDoc& buffer) override;
    TFastArchiveStringPool& GetStringPool() override;

private:
    const NRTYServer::TIndexerConfig& IndexerConfig;
    const TRTYFastArchiveConfig& ComponentConfig;

    TBulkFastArchive BulkArchive;
    TMutex ArchiveLock;
};
