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

namespace NRTYDeploy {

    bool IScript::CommandPermitted(IDeployInfoRequest& request) {
        const IUserAccessControl::TPermissions& perm = request.GetUserAccessControl().GetPermissions();
        if (perm.User == "no_control")
            return true;
        IUserAccessControl::TUsedResources resources;
        FillUsedResources(resources, request);
        if (perm.Resources.Services.find("all_services") != perm.Resources.Services.end())
            return true;
        if (resources.Services.find("all_services") != resources.Services.end())
            return false;
        for (IUserAccessControl::TServicesSet::const_iterator i = resources.Services.begin(); i != resources.Services.end(); ++i)
            if (perm.Resources.Services.find(*i) == perm.Resources.Services.end())
                return false;
        return true;
    }

    void IScript::FillUsedResources(IUserAccessControl::TUsedResources& result, IDeployInfoRequest& /*request*/) {
        result.Services.insert("all_services");
    }

    bool IScriptWithTask::Process(IDeployInfoRequest& request) {
        TClusterTask::TPtr task = DoBuildTask(request);
        if (!task)
            return false;
        task->BuildTask();
        if (task->GetCurrentStatus() == TClusterTask::ctsEnqueued) {
            request.Output() << "HTTP/1.1 200 \r\n\r\n";
            request.Output() << task->GetId() << Endl;
        } else if (task->GetResultStatus() == TClusterTask::rsSuspended) {
            request.Output() << "HTTP/1.1 200 Suspended\r\n\r\n";
            request.Output() << task->GetId() << Endl;
        } else if (task->GetResultStatus() == TClusterTask::rsDuplication) {
            request.Output() << "HTTP/1.1 400 \r\n\r\n";
            request.Output() << "duplication" << Endl;
        } else {
            request.Output() << "HTTP/1.1 500 \r\n\r\n";
            request.Output() << "Fail code: " << RSToString(task->GetResultStatus()) << ". Message: " << task->GetStatusInfo();
            return false;
        }
        return true;
    }
}
