#include "script_controller.h"

#include <library/cpp/logger/global/global.h>

namespace NRTYDeploy {
    TScriptController::TScriptController(IVersionedStorage& storage, const TString& id)
        : Storage(storage)
        , Id(id)
    {
    }

    void TScriptController::Start() {
    }

    void TScriptController::Finish() {
        Storage.RemoveNode(GetPath());
    }

    bool TScriptController::IsExecutable() {
        return !GetTaskState()["suspended"].GetBoolean();
    }

    bool TScriptController::SetTaskSuspended(bool suspended) {
        TAbstractLock::TPtr lock = Storage.WriteLockNode(GetPath());
        if (!lock || !lock->IsLocked())
            return false;

        NJson::TJsonValue json = GetTaskState(false);
        json["suspended"] = suspended;
        SetTaskStateUnsafe(json);
        return true;
    }

    void TScriptController::SetTaskStateUnsafe(NJson::TJsonValue& json) {
        Storage.SetValue(GetPath(), json.GetStringRobust(), true, false);
    }

    NJson::TJsonValue TScriptController::GetTaskState(bool lock) {
        TString state;
        NJson::TJsonValue result(NJson::JSON_MAP);
        if (!Storage.GetValue(GetPath(), state, -1, lock) || !NJson::ReadJsonFastTree(state, &result)) {
            result["suspended"] = false;
        }
        return result;
    }

    TString TScriptController::GetPath() {
        return "/cluster_tasks/" + Id + ".state";
    }
}
