function [id, wasEnabled] = serializationProfiling(action, isStart, id, numBytes)
%serializationProfiling Gateway to pool serialization

% Copyright 2017-2019 The MathWorks, Inc.

persistent ENABLED
if isempty(ENABLED)
    ENABLED = false;
end
wasEnabled = ENABLED;

if nargin == 4 && ~ENABLED
    % Early return for the most common case.
    return
end

switch action
  case 'enable'
    ENABLED = true;
    id = [];
  case 'disable'
    ENABLED = false;
    id = [];
  case 'isenabled'
    % wasEnabled is already set.
    id = [];
  case 'serialize'
    id = iActuallyReport(action, isStart, id, numBytes);
  case 'deserialize'
    id = iActuallyReport(action, isStart, id, numBytes);
end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function id = iActuallyReport(type, isStart, id, numBytes)

if isempty(id)
    id = com.mathworks.toolbox.distcomp.util.MatlabRefStore.getNextMatlabInvocationId();
end

sessionObj = parallel.internal.pool.workerSession();
if isempty(sessionObj)
    pool = parallel.internal.pool.PoolArrayManager.getCurrent();
    sessionObj = pool.hGetClient();
end
isSerialize = strcmp(type, 'serialize');
sessionObj.Session.notifySerializationStatus(isSerialize, isStart, id, numBytes);
end
