function aHandler = workerMessageHandler( )
%workerMessageHandler create internal message handler for workers.
%
% The message handler accepts a level number and a message, and routes them
% to the worker logger.

% Copyright 2006-2021 The MathWorks, Inc.

% PCT_Java_Transition_TODO g2364333 - Remove
% ExperimentalVersion switching code and java paths
experimentalVersions = parallel.internal.apishared.ExperimentalVersions.get();
handlers = {};
if experimentalVersions.requireJavaLogging()
    handlers = {iCreateJavaHandler()};
end
if experimentalVersions.requireCppLogging()
    handlers{end+1} = @(message, level) parallel.internal.logging.log(level, message);
end

aHandler = @(msg, levelNum) cellfun(@(h) h(msg, levelNum), handlers);
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function aHandler = iCreateJavaHandler()
aHandler = @nMessageHandler;
workerLogger = com.mathworks.toolbox.distcomp.mjs.worker.PackageInfo.LOGGER;
% Defend against other code resetting the global LogManager
% see g1095813.
workerLogger.setLevel(java.util.logging.Level.ALL);
    function nMessageHandler(msg, levelNum)
    % Do nothing if log level is invalid
    if nargin ~= 2
        return
    end
    lvl = com.mathworks.toolbox.parallel.pctutil.logging.DistcompLevel.getLevelFromValue(levelNum);
    workerLogger.log(lvl, msg);
    end
end
