#include "env.h"

#include <library/cpp/coroutine/engine/helper.h>

namespace NBalancerServer::NTesting {

void TEnv::Start(TServerCallback callback, TOptions options, bool useTwoPorts) {
    if (useTwoPorts) {
        options.SslPort = SslPort;
        options.Port = Port;
    } else if (options.SslConfigPath) {
        options.SslPort = SslPort;
    } else {
        options.Port = Port;
    }

    Server = MakeHolder<TStandaloneServer>(callback, options);

    ServerPool.Start(1, 0);

    UNIT_ASSERT(!NCoro::TryConnect("localhost", Port));
    UNIT_ASSERT(!NCoro::TryConnect("localhost", SslPort));

    UNIT_ASSERT(ServerPool.AddFunc([this]() {
        try {
            this->Server->Run();
        } catch (...) {
            UNIT_ASSERT_C(false, CurrentExceptionMessage());
            throw;
        }
    }));

    if (options.Port) {
        UNIT_ASSERT(NCoro::WaitUntilConnectable("localhost", options.Port, TDuration::Seconds(10)));
    }

    if (options.SslPort) {
        UNIT_ASSERT(NCoro::WaitUntilConnectable("localhost", options.SslPort, TDuration::Seconds(10)));
    }
}

void TEnv::Stop() {
    if (Server) {
        Server->Stop();
        ServerPool.Stop();

        UNIT_ASSERT(!NCoro::TryConnect("localhost", Port));
        UNIT_ASSERT(!NCoro::TryConnect("localhost", SslPort));
    }
}

TEnv::~TEnv() {
    Stop();
}

}  // namespace NBalancerServer::NTesting

