#include "component.h"

#include "builder.h"

#include <saas/rtyserver/config/config.h>
#include <saas/rtyserver/config/realm_config.h>

#include <robot/library/oxygen/indexer/processor/protos/config.pb.h>

namespace NRTYServer {
    namespace {
        const TString STATIC_FILES = "STATIC_FILES";

        IIndexComponent::TFactory::TRegistrator<TStaticFilesComponent> registerThis(STATIC_FILES);

        const NOxygen::TOxygenOptions& GetRealmConfig(const TRTYServerConfig& config, const TString& realmConfigName) {
            const NOxygen::TOxygenOptions* oxyOptions = config.GetRealmListConfig().GetRealmConfigByConfigName(realmConfigName).GetOxygenOptions();
            if (!oxyOptions) {
                ythrow yexception() << "No OxygenOptions for realm: " << realmConfigName;
            }
            return *oxyOptions;
        }
    }

    TStaticFilesComponent::TStaticFilesComponent(const TRTYServerConfig& config)
        : IIndexComponent(config.ComponentsSet.contains(STATIC_FILES))
        , Config(config)
    {
    }

    TString TStaticFilesComponent::GetName() const {
        return STATIC_FILES;
    }

    bool TStaticFilesComponent::IsCommonSearch() const {
        return false;
    }

    TBaseIndexComponent::TPriorityInfo TStaticFilesComponent::GetPriority() const {
        return TPriorityInfo(STATIC_FILES_COMPONENT_PRIORITY);
    }

    THolder<IIndexComponentBuilder> TStaticFilesComponent::CreateBuilder(const TBuilderConstructionContext& context) const {
        return MakeHolder<TStaticFilesBuilder>(GetName(), GetRealmConfig(Config, context.RealmName));
    }

    THolder<IIndexComponentManager> TStaticFilesComponent::CreateManager(const TManagerConstructionContext&) const {
        return nullptr;
    }

    IComponentParser::TPtr TStaticFilesComponent::BuildParser() const {
        return nullptr;
    }

    IParsedEntity::TPtr TStaticFilesComponent::BuildParsedEntity(IParsedEntity::TConstructParams&) const {
        return nullptr;
    }

    bool TStaticFilesComponent::DoAllRight(const TNormalizerContext& context) const {
        const auto realm = context.GetRealmName();
        RepairStaticFiles(GetRealmConfig(Config, realm), context.Dir.PathName(), "DoAllRight");
        return true;
    }

    void TStaticFilesComponent::CheckAndFix(const TNormalizerContext& context) const {
        const auto realm = context.GetRealmName();
        RepairStaticFiles(GetRealmConfig(Config, realm), context.Dir.PathName(), "CheckAndFix");
    }

    bool TStaticFilesComponent::CheckAlways() const {
        return true;
    }

    const IIndexComponent::TIndexFiles& TStaticFilesComponent::GetIndexFiles() const {
        return IndexFiles;
    }

    bool TStaticFilesComponent::DoMerge(const TMergeContext& context) const {
        for (auto& dest : context.Context.Dests) {
            BuildAndReplaceStaticFiles(GetRealmConfig(Config, context.RealmName), dest, "Merge");
        }
        return true;
    }
}
