#pragma once

#include "ddk_globals.h"
#include "ddk_config.h"
#include "metrics.h"

#include <saas/rtyserver/config/config.h>
#include <saas/rtyserver/config/common_indexers_config.h>
#include <saas/rtyserver/indexer_core/abstract_model.h>
#include <saas/rtyserver/indexer_core/parsed_document.h>
#include <saas/rtyserver/components/erf/erf_component.h>

class TDDKComponentConfig;
class TRTYDDKManager;

class TRTYDDKIndexComponent: public TRTYErfIndexComponent {
public:
    typedef TRTYErfIndexComponent TBase;

public:
    explicit TRTYDDKIndexComponent(const TRTYServerConfig& config);

    THolder<NRTYServer::IIndexComponentBuilder> CreateBuilder(const NRTYServer::TBuilderConstructionContext& context) const override;
    THolder<NRTYServer::IIndexComponentManager> CreateManager(const NRTYServer::TManagerConstructionContext& context) const override;
    NRTYServer::IParsedEntity::TPtr BuildParsedEntity(NRTYServer::IParsedEntity::TConstructParams& params) const override;
    NRTYServer::IComponentParser::TPtr BuildParser() const override;

    bool CheckConfig() const override {
        const TDDKComponentConfig* ddkConf = Config.ComponentsConfig.Get<TDDKComponentConfig>(DDK_COMPONENT_NAME);
        if (ddkConf) {
            if (ddkConf->GetDefaultLifetimeMinutes() && Config.GetCommonIndexers().RejectDuplicates) {
                ERROR_LOG << "DefaultLifetimeMinutes in ddk is incorrect option with RejectDuplicates in one time" << Endl;
                return false;
            }
        }
        return TRTYErfIndexComponent::CheckConfig();
    }

    static bool IsUsedStatic(const TRTYServerConfig& config);

    bool CheckAlways() const override {
        return DDKConfig.GetCheckAlways();
    }

    TString GetName() const override {
        return DDK_COMPONENT_NAME;
    }

    bool DoMerge(const NRTYServer::TMergeContext& rtyContext) const override;
    bool DoAllRight(const NRTYServer::TNormalizerContext& context) const override;
    void CheckAndFix(const NRTYServer::TNormalizerContext& context) const override;
    THolder<TPruningConfig::ICalcer> CreatePruningCalcer(const NRTYServer::IIndexManagersStorage* managers) const override;

    TPriorityInfo GetPriority() const override {
        TPriorityInfo result = TRTYErfIndexComponent::GetPriority();
        result.ComponentPriority = DDK_COMPONENT_PRIORITY;
        result.ManagerPriority = DDK_MANAGER_PRIORITY;
        return result;
    }

private:
    bool CheckRemap(const TRTYDDKManager& ddk, const NRTYServer::TNormalizerContext& context) const;
    bool CheckHashes(const TRTYDDKManager& ddk, const NRTYServer::TNormalizerContext& context) const;
    TAutoPtr<TRTYDDKManager> CreateManager(const TString& directory) const;
private:
    bool IsReadOnly = false;
    const TDDKComponentConfig& DDKConfig;
    mutable TAutoGlobal<TDDKMetrics> Metrics;

private:
    static TFactory::TRegistrator<TRTYDDKIndexComponent> Registrator;
};
