#include "control_task.h"

#include <saas/deploy_manager/scripts/cluster/cluster_task.h>
#include <saas/deploy_manager/scripts/cluster/script_controller.h>
#include <saas/deploy_manager/server/client/client.h>

namespace NRTYDeploy {
    bool TScriptControlTask::Process(IDeployInfoRequest& request) {
        TString taskId = request.GetRD().CgiParam.Get("task_id");
        if (!taskId) {
            request.Output() << "HTTP/1.1 400 \r\n\r\n";
            request.Output() << "Task id was not specified";
            return false;
        }

        TString action = request.GetRD().CgiParam.Get("action");
        if (!action) {
            request.Output() << "HTTP/1.1 400 \r\n\r\n";
            request.Output() << "Action was not specified";
            return false;
        }

        if (action == "resume") {
            TClusterTask task(taskId, &request, 16);
            if (task.GetCurrentStatus() != TClusterTask::ctsLoaded) {
                request.Output() << "HTTP/1.1 400 \r\n\r\n";
                request.Output() << "Can't load task: " << task.GetStatusInfo() << "/" << RSToString(task.GetResultStatus());
                return false;
            }

            TScriptController controller(request.GetStorage(), taskId);
            if (!controller.SetTaskSuspended(false)) {
                request.Output() << "HTTP/1.1 500 \r\n\r\n";
                return false;
            }
            task.EnqueueTask();
            if (task.GetCurrentStatus() != TClusterTask::ctsEnqueued) {
                request.Output() << "HTTP/1.1 500 \r\n\r\n";
                request.Output() << "Can't enqueue task: " << task.GetStatusInfo() << "/" << RSToString(task.GetResultStatus());
                return false;
            }
        } else if (action == "suspend" || action == "cancel") {
            TScriptController controller(request.GetStorage(), taskId);
            if (!controller.SetTaskSuspended(true)) {
                request.Output() << "HTTP/1.1 500 \r\n\r\n";
                return false;
            }
        } else {
            request.Output() << "HTTP/1.1 400 \r\n\r\n";
            request.Output() << "Invalid action '" + action + "'";
            return false;
        }

        request.Output() << "HTTP/1.1 200 \r\n\r\n";
        request.Output() << "OK";
        return true;
    }

    IScript::TFactory::TRegistrator<TScriptControlTask> TScriptControlTask::Registrator("control_task");
}
