#include "retry.h"

#include <balancer/kernel/balancer/algorithm.h>
#include <balancer/kernel/balancing/backend.h>
#include <balancer/modules/balancer/policies/policy_factory.h>

namespace NSrvKernel::NRetry {

IBackend* TRetryPolicy::Next(IAlgorithm* algo, bool fastAttempt) noexcept {
    IBackend* next = Slave_->Next(algo, fastAttempt);
    if (next == nullptr) {
        algo->Reset();
        return Slave_->Next(algo, fastAttempt);
    }
    return next;
}


POLICY_FACTORY_BASE(retry_policy, TPolicyFactoryWithSlave), public TModuleParams {
    TPolicyFactory(const TModuleParams& mp)
        : TModuleParams(mp)
    {
        Config->ForEach(this);
        CheckConfiguration();
    }

    THolder<IPolicy> ConstructPolicy(const TStepParams& params) noexcept override {
        return MakeHolder<TRetryPolicy>(TPolicyBase::ConstructPolicy(params));
    }

private:
    START_PARSE {
        if (Configure(key, Copy(value->AsSubConfig()))) {
            return;
        }
    } END_PARSE
};

INodeHandle<IPolicyFactory>* Handle() {
    return TPolicyFactory::Handle();
}

}  // namespace NSrvKernel::NRetry
