#include "handler.h"

#include <balancer/kernel/http/parser/http.h>
#include <balancer/kernel/module/conn_descr.h>
#include <balancer/kernel/srcrwr/srcrwr_addrs.h>
#include <balancer/kernel/srcrwr/srcrwr_helper.h>

using namespace NSrvKernel;

namespace NModSrcrwr {

THandler::THandler(THolder<NSrcrwr::IHelper>&& helper)
    : SrcrwrHelper_(std::move(helper))
{
    Y_ASSERT(SrcrwrHelper_);
}

bool THandler::Handle(const NSrvKernel::TConnDescr& descr, const TString& id) const
{
    if (!descr.Properties || !descr.Request) {
        return false;
    }

    // Check ID, get addresses from cgi for this srcrwr ID
    TVector<NSrcrwr::TAddr> addrs;
    if (!SrcrwrHelper_->GetAddrs(*descr.Request, id, addrs)) {
        return false;
    }

    // Check that it hasn't been handled, and write it to header
    if (!SrcrwrHelper_->WriteHeader(*descr.Request, id)) {
        return false;
    }

    // Store addresses for using in redirect
    auto& storage = descr.Properties->SrcrwrAddrs;
    Y_ASSERT(!storage);
    storage = new NSrcrwr::TAddrs();
    storage->SetAddrs(std::move(addrs));

    return true;
}

void THandler::CleanUp(const NSrvKernel::TConnDescr& descr) const
{
    if (!descr.Properties || !descr.Properties->SrcrwrAddrs) {
        return;
    }
    delete descr.Properties->SrcrwrAddrs;
    descr.Properties->SrcrwrAddrs = nullptr;
}

}