#pragma once

#include "globals.h"
#include "l2_core.h"
#include "l2_builder.h"
#include "l2_parser.h"
#include "l2_disk_manager.h"
#include "l2_memory_manager.h"
#include <saas/rtyserver/factors/function.h>
#include <saas/rtyserver/indexer_core/document_parser.h>
#include <saas/rtyserver/components/fullarchive/disk_manager.h>
#include <saas/rtyserver/components/fullarchive/light_entity.h>

namespace NRTYServer {
    class TL2RawIndexer: public TL2ComponentParserBase {
    public:
        using TL2ComponentParserBase::TL2ComponentParserBase;

        void Parse(TParsingContext& context) const override {
            // This simply stores document.DocumentProperties[ComponentName] as an L2 blob
            // Not really useful, but nice for tests

            const TMessage::TDocument& document = context.Document;
            const TString* data = nullptr;

            for (const auto& property : document.GetDocumentProperties()) {
                if (property.GetName() == ComponentName) {
                    data = &property.GetValue();
                    break;
                }
            }

            if (data) {
                TBlob l2blob = TBlob::FromString(*data);
                auto* entity = GetComponentEntity(context);
                WriteRawData(entity, context, std::move(l2blob));
            }
        }
    };

    class TL2RawManager: public TL2ComponentDiskManagerBase {
    public:
        using TL2ComponentDiskManagerBase::TL2ComponentDiskManagerBase;

        TString GetRawL2Data(ui32 docId) const {
            TBlob rawData = FetchRawL2Data(docId);
            return {rawData.AsCharPtr(), rawData.Length()};
        }

        virtual void GetExportedFunctions(NRTYFeatures::TImportedFunctionsBuilder& exports) const override {
            exports.AddGta(&TL2RawManager::GetRawL2Data, this, "L2_RawData");
        }
    };

    class TL2Normalizer;

    class TL2RawBlob: public IL2ComponentCore {
    public:
        using TDiskManager = TL2RawManager;
        using TMemoryManager = TL2ComponentMemoryManagerBase;
        using TBuilder = TL2ComponentBuilder;
        using TDocEntity = TRTYFullArchiveLightEntity;
        using TParser = TL2RawIndexer;
        using TNormalizer = TL2Normalizer;

    public:
        virtual TStringBuf GetName() const override {
            return L2ArcComponentName;
        }
    };
}
