function checkAndIssueWebServiceWarnings(serviceInfo)
% Check serviceInfo for messages that require warnings to be issued in MATLAB
%
%   Web services return messages in their response objects. This function
%   checks the messages and issues warnings appropriately based on the
%   suggested message frequency.
%
%   Possible message frequencies include:
%
%       PER_SESSION, PER_CLUSTER, ALWAYS
%
%   (see com.mathworks.webservices.clients.cloudcenter.CloudCenterMessage.Frequency)

%   Copyright 2015-2020 The MathWorks, Inc.

import parallel.internal.types.CloudCenterMessageFrequency

messageCache = parallel.internal.cloud.currentWebServiceMessagesCache();

% The messages are stored in a java.util.List
allMessages = serviceInfo.messages;

for messageIdx = 1:length(allMessages)
    messageObj = allMessages(messageIdx);
    messageFrequency = CloudCenterMessageFrequency.fromCloudCenterName(...
                       messageObj.Frequency);
    messageId = messageObj.MwMessageID;
    messageText = messageObj.MessageText;
    
    if messageFrequency == CloudCenterMessageFrequency.PerSession
        % This is a per-session message, check our persistent map to see if we've
        % already issued a warning for this session and if not, issue it and add
        % it to the map.
        if ~messageCache.hasMessageFor(messageId)
            parallel.internal.warningNoBackTrace(messageId, '%s', messageText);
            messageCache.addMessage(messageId, messageText);
        end

    elseif messageFrequency == CloudCenterMessageFrequency.PerCluster
        % This is a per-cluster message, check the persistent map to see if we've
        % already issued a warnings for this cluster and if not, issue it and add
        % it to the map.

        % We're using cluster id since this is tied to the Cloud Center
        % Messages. 
        clusterId = messageObj.ClusterID;

        % We're assuming that there is always a cluster name, we should assert
        % this is always true.
        assert(~isempty(clusterId), 'Cannot use an empty clusterId as a key');

        % We need a key which contains both the cluster id and the message id.
        clusterKey = [messageId ';' clusterId];
        if ~messageCache.hasMessageFor(clusterKey)
            parallel.internal.warningNoBackTrace(messageId, '%s', messageText);
            messageCache.addMessage(clusterKey, messageText);
        end
        
    elseif messageFrequency == CloudCenterMessageFrequency.Always
        parallel.internal.warningNoBackTrace(messageId, '%s', messageText);
    else
        % We should not be able to get here, because converting to the
        % MATLAB enum from the Cloud Center string enum should already check the enum
        % value is correct.
        assert(false, sprintf('Unknown message frequency: %s', messageFrequency));
    end
end
