#include "request_executor.h"
#include "nanny_request.h"
#include <saas/deploy_manager/config/config.h>
#include <library/cpp/logger/global/global.h>


TNannyRequestExecutor::TNannyRequestExecutor(const TDeployManagerConfig::TNannyConfig& nannyConfig)
    : NannyConfig(nannyConfig)
{
}

bool TNannyRequestExecutor::ExecuteRequest(IRequest& request, bool& isFatal, const int maxRetries) {
    int retries = 0;
    while (retries < maxRetries) {
        try {
            NUtil::THttpReply reply;
            if (request.Execute(reply)) {
                if (reply.Code() == 200) {
                     isFatal = false;
                     return request.Parse(reply);
                } else if (reply.Code() == 429) {
                    WARNING_LOG << "Nanny limit expired (" << reply.Content() << ") - retry... " << retries << Endl;
                    isFatal = false;
                } else if (reply.Code() / 100 == 4) {
                    ERROR_LOG << "User error with nanny usage " <<  reply.Code() << ": " << reply.Content() << Endl;
                    isFatal = false;
                    return false;
                } else {
                    ERROR_LOG << "Nanny error " <<  reply.Code() << ": " << reply.Content() << " - retry... " << retries << Endl;
                    isFatal = true;
                }
            } else {
                ERROR_LOG << "IRequest::Execute failed" << Endl;
                isFatal = true;
            }
        } catch (...) {
            ERROR_LOG << "Can't use nanny: " << CurrentExceptionMessage() << " - retry... " << retries << Endl;
            isFatal = true;
        }
        retries++;
        if (retries < maxRetries) {
            Sleep(NannyConfig.InterSendTimeout);
        }
    }
    return false;
}

