#include "execute_script.h"

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

#include <util/stream/str.h>
#include <util/stream/zlib.h>
#include <library/cpp/string_utils/base64/base64.h>

namespace NDaemonController {
    NJson::TJsonValue TExecuteScriptAction::DoSerializeToJson() const {
        NJson::TJsonValue result;
        result.InsertValue("direct", Script.Serialize());
        return result;
    }

    void TExecuteScriptAction::DoDeserializeFromJson(const NJson::TJsonValue& json) {
        NJson::TJsonValue::TMapType map;
        CHECK_WITH_LOG(json.GetMap(&map));
        CHECK_WITH_LOG(Script.Deserialize(map["direct"]));
    }

    bool TExecuteScriptAction::GetPostContentStart(TString& result) const {
        TStringStream compressed;
        {
            TZLibCompress compress(&compressed, ZLib::ZLib);
            NJson::TJsonValue json(Script.Serialize());
            NJson::WriteJson(&compress, &json);
        }
        result = Base64Encode(compressed.Str());
        return true;
    }

    void TExecuteScriptAction::InterpretTaskReply(TAsyncTaskExecutor::TTask::TStatus taskStatus, const NJson::TJsonValue& result) {
        const NJson::TJsonValue::TMapType& map = result.GetMap();
        NJson::TJsonValue::TMapType::const_iterator i = map.find("script");
        if (i != map.end() && !Script.Deserialize(i->second))
            Fail("invalid reply: " + result.GetStringRobust());
        else
            TControllerAsyncAction::InterpretTaskReply(taskStatus, result);
    }

    TExecuteScriptAction::TFactory::TRegistrator<TExecuteScriptAction> TExecuteScriptAction::Registrator(EXECUTE_SCRIPT_ACTION_NAME);
}
