#include "backend.h"

#include <balancer/kernel/module/iface.h>
#include <util/generic/adaptor.h>

namespace NSrvKernel {
    TBackendDescriptor::TBackendDescriptor(TString name, THolder<IModule> mod, double weight)
        : Name_(name)
        , Module_(std::move(mod))
        , Weight_(weight)
    {}

    TBackendDescriptor::TBackendDescriptor(TModuleParams mp, const TString& name)
        : Name_(name)
    {
        if (!mp.Modules) {
            mp.Modules = &Modules_;
        }
        ParseMap(mp.Config, [&](auto& key, auto* value) {
            ON_KEY("weight", Weight_) {
                return;
            }
            Module_ = mp.Loader->MustLoad(key, mp.Copy(value->AsSubConfig()));
        });

        Y_ENSURE_EX(Module_, TConfigParseError() << "no module configured");

        for (auto& i : Modules_) {
            i.Finalize();
        }
    }

    void TBackendDescriptor::Init(IWorkerCtl* process) {
        for (auto& i : Reversed(Modules_)) {
            i.Init(process);
        }
    }

    void TBackendDescriptor::Dispose(IWorkerCtl* process) {
        for (auto& i : Modules_) {
            i.Dispose(process);
        }
    }
}
