#include "server.h"

#include <saas/library/daemon_base/daemon/controller.h>

DEFINE_CONTROLLER_COMMAND(THttpProxyRTYServer, get_timestamp, "get timestamp and metrics")
    TController::TGuardServer gs = GetServer(true);
    THttpProxyRTYServer& server = gs->GetLogicServer().GetMeAs<THttpProxyRTYServer>();
    NJson::TJsonValue result;
    for (auto&& service : server.GetConfig().GetServiceMap()) {
        const TString& name = service.first;
        TServiceMetric::TResult data = server.GetMetrics().GetResult(name);

        NJson::TJsonValue s;
        s.InsertValue("timestamp", data.IncTimestamp);
        s.InsertValue("server_error_rate", data.FailRequests.AvgRate);
        s.InsertValue("user_error_rate", data.UserFailRequests.AvgRate);
        s.InsertValue("success_rate", data.OkRequests.AvgRate);

        const float serverErrorFraction = (data.IncRequests.AvgRate > 0.001f)
            ? data.FailRequests.AvgRate / data.IncRequests.AvgRate : 0;
        const float userErrorFraction = (data.IncRequests.AvgRate > 0.001f)
            ? data.UserFailRequests.AvgRate / data.IncRequests.AvgRate : 0;
        s.InsertValue("server_error_fraction", serverErrorFraction);
        s.InsertValue("user_error_fraction", userErrorFraction);
        result.InsertValue(name, s);
    }
    Write("services", result);
END_CONTROLLER_COMMAND

DEFINE_CONTROLLER_COMMAND(THttpProxyRTYServer, purge_queue, "Clean service or queue, arguments: purge_queue_service (name of service) or name (name of queue)")
    TDeferredMessagesQueue& deferredMessagesQueue = GetServer(true)->GetLogicServer().GetMeAs<THttpProxyRTYServer>().GetDeferredMessagesQueue();
    const TCgiParameters& cgi = GetCgi();
    if (cgi.Has("purge_queue_service")) {
        deferredMessagesQueue.PurgeService(cgi.Get("purge_queue_service"));
    } else if (cgi.Has("name")) {
        deferredMessagesQueue.PurgeQueue(cgi.Get("name"));
    } else {
        throw yexception() << "either queue name or service name should be present";
    }
    Write("result", "success");
END_CONTROLLER_COMMAND
