#include "handler.h"

#include <balancer/kernel/srcrwr/srcrwr_addrs.h>
#include <util/string/split.h>


using namespace NSrvKernel;

namespace NModSrcrwrExt {

namespace {
constexpr char Delimiter = '-';
}

bool THandler::Handle(const TString& host, NSrcrwr::TAddrs*& addrs) const
{
    Y_ASSERT(!addrs);

    TVector<NSrcrwr::TAddr> srcrwrAddr;
    if (!Parse(host, srcrwrAddr)) {
        return false;
    }
    addrs = new NSrcrwr::TAddrs();
    addrs->SetAddrs(std::move(srcrwrAddr));

    return true;
}

void THandler::CleanUp(NSrcrwr::TAddrs*& addrs) const
{
    if (!addrs) {
        return;
    }
    delete addrs;
    addrs = nullptr;
}

// Example:
// Host in header: m-man-pbcznloiqpakow2g-24536-yp.tun.si.turbopages.org
// Actual host: pbcznloiqpakow2g.man.yp-c.yandex.net:24536
bool THandler::Parse(const TString& host, TVector<NSrcrwr::TAddr>& addrs) const noexcept try {
    Y_ASSERT(!host.empty() && addrs.empty());

    const TVector<TString> tokens = StringSplitter(host).Split(Delimiter);
    if (tokens.empty()) {
        return false;
    }

    uint64_t delta = 1;
    // Remove prefix, if any
    if (!PrefixToRemove_.empty() && PrefixToRemove_ == tokens[0]) {
        delta = 0; // count from prefix
    }

    if (tokens.size() < 5 - delta) { // if greater it means, that domains contain '-'
        return false;
    }

    NSrcrwr::TAddr addr{tokens[2 - delta] + '.' + tokens[1 - delta] + '.' + Domains_, "",
                        FromString<TIpPort>(tokens[3 - delta])};

    addrs.push_back(std::move(addr));

    return true;
} catch(...) {
    return false;
}

}
