#include <library/cpp/testing/unittest/registar.h>

#include <balancer/modules/balancer/backends_factory.h>

#include "module.h"

using namespace NModBalancer;

Y_UNIT_TEST_SUITE(TestBalancer2Attempts) {
    class TBackends
        : public IBackends
    {
        THolder<IAlgorithm> ConstructAlgorithm(const TStepParams&) noexcept final {
            return nullptr;
        }

        void DumpBackends(NJson::TJsonWriter&, const IWorkerCtl&) const noexcept final {}
        void DumpWeightsFileTags(NJson::TJsonWriter&, const IWorkerCtl&) const noexcept final {}
        void DumpBalancingState(NJson::TJsonWriter&, const IWorkerCtl&) const noexcept final {}
    };

    Y_UNIT_TEST(Default) {
        TBackends backends;
        TAttempts attempts(1);

        UNIT_ASSERT_VALUES_EQUAL(attempts.GetOriginalValue(), 1);
        UNIT_ASSERT_VALUES_EQUAL(attempts.Get(backends.Size()), 1);
    }

    Y_UNIT_TEST(Config) {
        TBackends backends;
        TAttempts attempts(1);

        attempts.ParseConfig("7");
        UNIT_ASSERT_VALUES_EQUAL(attempts.GetOriginalValue(), 7);
        UNIT_ASSERT_VALUES_EQUAL(attempts.Get(backends.Size()), 7);
    }

    Y_UNIT_TEST(Override) {
        TBackends backends;
        TAttempts attempts(1);

        attempts.ParseConfig("7");
        UNIT_ASSERT_VALUES_EQUAL(attempts.GetOriginalValue(), 7);
        UNIT_ASSERT_VALUES_EQUAL(attempts.Get(backends.Size()), 7);

        attempts.Override("3");
        UNIT_ASSERT_VALUES_EQUAL(attempts.GetOriginalValue(), 7);
        UNIT_ASSERT_VALUES_EQUAL(attempts.Get(backends.Size()), 3);

        attempts.Override("");
        UNIT_ASSERT_VALUES_EQUAL(attempts.GetOriginalValue(), 7);
        UNIT_ASSERT_VALUES_EQUAL(attempts.Get(backends.Size()), 7);
    }

    Y_UNIT_TEST(BackendsCount) {
        TBackends backends;

        TAttempts attempts(1);

        attempts.ParseConfig("count_backends");
        for (auto i : xrange(7)) {
            backends.Add(MakeHolder<TBackendDescriptor>(ToString(i), nullptr));
        }
        UNIT_ASSERT_VALUES_EQUAL(attempts.GetOriginalValue(), 1);
        UNIT_ASSERT_VALUES_EQUAL(attempts.Get(backends.Size()), 7);

        for (auto i : xrange(3)) {
            backends.Add(MakeHolder<TBackendDescriptor>(ToString(i), nullptr));
        }
        UNIT_ASSERT_VALUES_EQUAL(attempts.GetOriginalValue(), 1);
        UNIT_ASSERT_VALUES_EQUAL(attempts.Get(backends.Size()), 10);

        attempts.Override("5");
        UNIT_ASSERT_VALUES_EQUAL(attempts.GetOriginalValue(), 1);
        UNIT_ASSERT_VALUES_EQUAL(attempts.Get(backends.Size()), 5);

        attempts.Override("xxx");
        UNIT_ASSERT_VALUES_EQUAL(attempts.GetOriginalValue(), 1);
        UNIT_ASSERT_VALUES_EQUAL(attempts.Get(backends.Size()), 10);
    }
}
