#include "action.h"

#include <library/cpp/json/writer/json_value.h>
#include <util/stream/str.h>
#include <library/cpp/json/json_reader.h>
#include <library/cpp/logger/global/global.h>

namespace NDaemonController {
    NJson::TJsonValue TSetConfAction::DoSerializeToJson() const {
        NJson::TJsonValue result = TSaveFileAction::DoSerializeToJson();
        result.InsertValue("file_data", FileData);
        return result;
    }

    void TSetConfAction::DoDeserializeFromJson(const NJson::TJsonValue& json) {
        TSaveFileAction::DoDeserializeFromJson(json);
        NJson::TJsonValue::TMapType map;
        CHECK_WITH_LOG(json.GetMap(&map));
        FileData = map["file_data"].GetStringRobust();
    }

    NJson::TJsonValue TSaveFileAction::DoSerializeToJson() const {
        NJson::TJsonValue result;
        result.InsertValue("file_name", FileName);
        if (Version >= 0)
            result.InsertValue("version", Version);
        return result;
    }

    void TSaveFileAction::DoDeserializeFromJson(const NJson::TJsonValue& json) {
        NJson::TJsonValue::TMapType map;
        CHECK_WITH_LOG(json.GetMap(&map));
        FileName = map["file_name"].GetStringRobust();
        if (map.contains("version"))
            Version = map["version"].GetIntegerRobust();
    }

    void TSaveFileAction::DoInterpretResult(const TString& result) {
        NJson::TJsonValue json;
        TStringInput si(result);
        if (!NJson::ReadJsonTree(&si, &json) || !json.Has("version")) {
            Fail(result);
        } else {
            Version = json["version"].GetIntegerRobust();
            Success("");
        }
    }

    TSetConfAction::TFactory::TRegistrator<TSetConfAction> TSetConfAction::Registrator(SET_CONF_ACTION_NAME);
}
