#include "events.h"
#include "module_face.h"

#include <util/generic/adaptor.h>

namespace NSrvKernel {

    TModuleParams::TModuleParams(
        IConfig* config,
        IModuleFactory* loader,
        ICtl* control,
        TModuleList* modules,
        const TResolvedHosts* resolvedHosts,
        TDisabledHosts* disabledHosts
    ) noexcept
        : Config(config)
        , Loader(loader)
        , Control(control)
        , Modules(modules)
        , ResolvedHosts_(resolvedHosts)
        , DisabledHosts_(disabledHosts)
    {}

    TModuleParams TModuleParams::Copy(IConfig* cfg) const noexcept {
        TModuleParams ret = *this;
        ret.Config = cfg;
        return ret;
    }

    void TModules::Init(IWorkerCtl* process) {
        TEventHandler& eventHandler = *process->EventHandler();
        for (auto& module: Reversed(*this)) {
            module.Init(process);
            const TEventHandler* const eh = module.EventHandler();
            if (eh && !eh->Empty()) {
                eventHandler.Unite(*eh);
            }
        }
    }

    void TModules::Finalize() {
        for (auto& module: *this) {
            module.Finalize();
        }
    }

    void TModules::Dispose(IWorkerCtl* process) {
        THashSet<const TEventHandler*> oldHandlers;
        for (auto& module: *this) {
            const TEventHandler* const eh = module.EventHandler();
            if (eh && !eh->Empty()) {
                oldHandlers.insert(eh);
            }
        }
        if (!oldHandlers.empty()) {
            process->EventHandler()->Remove(oldHandlers);
        }
        for (auto& module: *this) {
            module.Dispose(process);
        }
    }
}
