#include "action.h"

#include <library/cpp/json/json_reader.h>

namespace {
    void SerializeArrayToJson(NJson::TJsonValue& result, const TString& name, const TVector<TString>& values) {
        if (values.size()) {
            NJson::TJsonValue arrInfo;
            for (auto&& i : values) {
                arrInfo.AppendValue(i);
            }
            result.InsertValue(name, std::move(arrInfo));
        }
    }

    void DeserializeArrayFromJson(const NJson::TJsonValue& json, const TString& name, TVector<TString>& values) {
        if (json.Has(name)) {
            NJson::TJsonValue::TArray arr;
            CHECK_WITH_LOG(json[name].GetArray(&arr));
            for (auto&& i : arr) {
                values.push_back(i.GetStringRobust());
            }
        }
    }
}

namespace NDaemonController {

    NJson::TJsonValue TClusterControlAction::DoSerializeToJson() const {
        NJson::TJsonValue result;
        result.InsertValue("service", Service);
        result.InsertValue("ctype", CType);
        result.InsertValue("deploy_proxies", DeployProxies);
        SerializeArrayToJson(result, "replace_slots", ReplaceSlots);
        SerializeArrayToJson(result, "restore_slots", RestoreSlots);
        SerializeArrayToJson(result, "new_slots_pool", NewSlotsPool);
        SerializeArrayToJson(result, "copy_slots", CopySlotsPool);
        SerializeArrayToJson(result, "absent_slots", AbsentSlots);
        return result;
    }

    void TClusterControlAction::DoDeserializeFromJson(const NJson::TJsonValue& json) {
        Service = json["service"].GetStringRobust();
        CType = json["ctype"].GetStringRobust();
        DeserializeArrayFromJson(json, "new_slots_pool", NewSlotsPool);
        DeserializeArrayFromJson(json, "replace_slots", ReplaceSlots);
        DeserializeArrayFromJson(json, "restore_slots", RestoreSlots);
        DeserializeArrayFromJson(json, "copy_slots", CopySlotsPool);
        DeserializeArrayFromJson(json, "absent_slots", AbsentSlots);
        DeployProxies = !json.Has("deploy_proxies") || json["deploy_proxies"].GetBooleanRobust();
    }

    TClusterControlAction::TFactory::TRegistrator<TClusterControlAction> TClusterControlAction::Registrator(CLUSTER_CONTROL_ACTION_NAME);
}
