#include "admin_server.h"

#include <library/cpp/http/server/response.h>
#include <library/cpp/http/misc/parsed_request.h>
#include <library/cpp/json/json_writer.h>

#include <util/stream/null.h>
#include <util/stream/file.h>

TClientRequest* TAdminServer::CreateClient() {
    return new TAdminRequestReplier(this);
}

void TAdminServer::OnException() {
    // TODO: write into an errorlog with timestamps
    Cerr << CurrentExceptionMessage() << "\n";
}

bool TAdminRequestReplier::DoReply(const TReplyParams& params) {
    TParsedHttpRequest req(params.Input.FirstLine());
    params.Input.ReadAll(Cnull);
    if (req.Method != "GET") {
        params.Output << THttpResponse(HTTP_NOT_IMPLEMENTED);
    }
    if (req.Request == "/admin?action=shutdown") {
        Server_->OnShutdown();
        Server_->Shutdown();
        params.Output << THttpResponse(HTTP_OK);
    } else if (req.Request == "/admin?action=reopenlog") {
        Server_->OnReopenlog();
        params.Output << THttpResponse(HTTP_OK);
    } else {
        params.Output << THttpResponse(HTTP_NOT_FOUND);
    }
    return true;
}
