#include "http_utils.h"

#include <library/cpp/logger/global/global.h>

#include <util/folder/path.h>
#include <util/stream/file.h>
#include <util/string/cast.h>
#include <library/cpp/string_utils/url/url.h>

namespace {

    void DoRequest(const TString& host, ui32 port, const TStringBuf& relativeUrl, const TStringBuf& body, bool isPost, IOutputStream* output)
    {
        DEBUG_LOG << "About to " << (isPost ? "POST" : "GET") << ' ' << host << ':' << port << relativeUrl;

        TSimpleHttpClient client(host, port);
        if (isPost) {
            client.DoPost(relativeUrl, body, output);
        } else {
            client.DoGet(relativeUrl, output);
        }

        DEBUG_LOG << host << ':' << port << relativeUrl << "got success code";
    }

} // namespace anonymous

void NSaas::DoHttpGetRequest(const TString& host, ui32 port, const TStringBuf& relativeUrl, IOutputStream* output) {

    DoRequest(host, port, relativeUrl, /*body*/ TStringBuf(), /*isPost*/ false, output);
}

void NSaas::DoHttpPostRequest(const TString& host, ui32 port, const TStringBuf& relativeUrl, const TStringBuf& body,
    IOutputStream* output)
{
    DoRequest(host, port, relativeUrl, body, /*isPost*/ true, output);
}

void NSaas::DoDownloadFileViaHttp(const TString& url, const TString& destinationPath) {
    Y_ENSURE(TFsPath(destinationPath).Exists(), "dir doesn't exist: " << destinationPath);
    TFileOutput output(TFsPath(destinationPath) / TFsPath(GetPathAndQuery(url)).GetName());
    auto portStr = GetHostAndPort(CutSchemePrefix(url)).After(':');
    ui32 port = portStr.empty() ? 80 : FromString<ui32>(portStr);

    DoHttpGetRequest(TString{GetHost(CutSchemePrefix(url))}, port, GetPathAndQuery(url), &output);
}
