#pragma once

#include <library/cpp/http/io/stream.h>
#include <library/cpp/logger/global/global.h>

#include <util/network/socket.h>

namespace NRTYServer {
    class THttpOpHelper {
    public:
        static ui32 DoQuery(const TNetworkAddress& ep, const TStringBuf& host, const TString& query, TString* resultBuf) {
            TSocket s(ep);
            s.SetSocketTimeout(50, 0);
            s.SetZeroLinger();

            TSocketOutput so(s);
            THttpOutput output(&so);
            output.EnableKeepAlive(false);
            output.EnableCompression(false);

            output << "GET " << query << " HTTP/1.1"
                   << "\r\n";
            output << "Host: " << host << "\r\n";
            output << "\r\n";
            output.Finish();

            TSocketInput si(s);
            THttpInput input(&si);
            unsigned httpCode = ParseHttpRetCode(input.FirstLine());
            if (resultBuf)
                *resultBuf = input.ReadAll();
            return httpCode;
        }

        static bool SendCommand(const TNetworkAddress& ep, const TStringBuf& host, const TString& path) {
            Y_ENSURE(path.StartsWith("/"));
            try{
                TSocket s(ep);
                s.SetZeroLinger();

                SendMinimalHttpRequest(s, host, path);
                TSocketInput si(s);
                THttpInput input(&si);
                unsigned httpCode = ParseHttpRetCode(input.FirstLine());
                if (httpCode != 200) {
                    return false;
                }
            } catch (...) {
                ERROR_LOG << "Http request resulted in an exception:" << CurrentExceptionMessage() << Endl;
                return false;
            }
            return true;
        }
    };

}
