#include "action_replica.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>
#include <saas/deploy_manager/meta/cluster.h>
#include <saas/library/searchmap/parsers/json/json.h>

namespace NDaemonController {
    NJson::TJsonValue TAllocateSlotsReplicasAction::DoSerializeToJson() const {
        NJson::TJsonValue result;
        result.InsertValue("intervals", Intervals.SerializeToJson());
        result.InsertValue("allocator", Allocator.SerializeToJson());
        result.InsertValue("ctype", CType);
        result.InsertValue("service", Service);
        result.InsertValue("service_type", ServiceType);
        result.InsertValue("replicas_count", ReplicasCount);
        if (ResultPool.Size())
            result.InsertValue("result_pool", ResultPool.Serialize());
        return result;
    }

    void TAllocateSlotsReplicasAction::DoDeserializeFromJson(const NJson::TJsonValue& json) {
        CHECK_WITH_LOG(json.IsMap());
        if (!Intervals.DeserializeFromJson(json["intervals"]))
            Fail("Incorrect intervals data " + json["slots"].GetStringRobust());
        if (!Allocator.DeserializeFromJson(json["allocator"]))
            Fail("Incorrect allocator data " + json["allocator"].GetStringRobust());
        CType = json["ctype"].GetStringRobust();
        Service = json["service"].GetStringRobust();
        ServiceType = json["service_type"].GetStringRobust();
        ReplicasCount = json["replicas_count"].GetIntegerRobust();
        if (json.Has("result_pool"))
            ResultPool.DeserializeFromJson(json["result_pool"]);
    }

    void TAllocateSlotsReplicasAction::DoInterpretResult(const TString& result) {
        if (!ResultPool.DeserializeFromString(result))
            Fail("incorrect slots pool: " + result);
        else
            Success("OK");
    }

    TAllocateSlotsReplicasAction::TFactory::TRegistrator<TAllocateSlotsReplicasAction> TAllocateSlotsReplicasAction::Registrator(ALLOCATE_SLOTS_REPLICAS_ACTION_NAME);
}
