#include "initializer_message.h"

#include <library/cpp/protobuf/json/json2proto.h>

#include <util/generic/algorithm.h>

namespace NSrvKernel {
    TChunkPtr SerializeMessage(const TInitializerMessage& msg) {
        // TODO(skalsin) Whe byte size long not working?
        TString str = msg.SerializeAsString();
        TChunkPtr chunk = NewChunk(str);
        chunk->Shrink(str.size());
        return chunk;
    }

    TInitializerMessage DeserializeMessage(const char* buf, size_t size) {
        TInitializerMessage msg;
        Y_ENSURE(msg.ParseFromArray(buf, size), "Invalid protocol buffers received");
        return msg;
    }

    const TInitializerMessage& ReloadSuccessful() {
        static TInitializerMessage message =
            NProtobufJson::Json2Proto<TInitializerMessage>("{\"ReloadState\": {\"Status\": \"SUCCESS\"}}");
        return message;
    }

    const TInitializerMessage& ReloadInProgress() {
        static TInitializerMessage message =
            NProtobufJson::Json2Proto<TInitializerMessage>("{\"ReloadState\":{\"Status\": \"IN_PROGRESS\"}}");
        return message;
    }

    TInitializerMessage ReloadFailed(const TString& error) {
        TInitializerMessage message;
        auto* reloadState = message.MutableReloadState();

        reloadState->SetStatus(TReloadState::FAILED);
        reloadState->SetError(error);
        return message;
    }

    const TInitializerMessage& GetReloadState() {
        static TInitializerMessage message = NProtobufJson::Json2Proto<TInitializerMessage>("{\"GetReloadState\": {}}");
        return message;
    }

    TInitializerMessage ShutdownMaster(TShutdownMaster::EShutdownReason reason) {
        TInitializerMessage message;
        auto* shutdownMsg = message.MutableShutdownMaster();
        shutdownMsg->SetReason(reason);

        return message;
    }

    const TInitializerMessage& CancelReload() {
        static TInitializerMessage message = NProtobufJson::Json2Proto<TInitializerMessage>("{\"CancelReload\": {}}");
        return message;
    }

    const TInitializerMessage& OldMasterExited() {
        static TInitializerMessage message = NProtobufJson::Json2Proto<TInitializerMessage>("{\"OldMasterExited\": {}}");
        return message;
    }

    const TInitializerMessage& OldMasterClosedUnistat() {
        static TInitializerMessage message = NProtobufJson::Json2Proto<TInitializerMessage>("{\"OldMasterClosedUnistat\": {}}");
        return message;
    }

    const TInitializerMessage& HealthMessage() {
        static TInitializerMessage message = NProtobufJson::Json2Proto<TInitializerMessage>("{\"HealthMessage\": {}}");
        return message;
    }

    bool IsReloadCompleted(const TReloadState& state) {
        return IsIn({TReloadState::SUCCESS, TReloadState::FAILED}, state.GetStatus());
    }
}
