function sysObj = setBlockMaskParamsOnObject(blkHndl,sysObj)
%SETBLOCKMASKPARAMSONOBJECT Set mask parameters from a Simulink block to an
%object as properties.
%
%   This function is for internal use only and may be removed in a future
%   release.

%   Copyright 2022 The MathWorks, Inc.

% See also:
% matlab.system.ui.SimulinkDescriptor/getBlockActionSystemObjectInstance
% https://blogs.mathworks.com/simulink/2015/08/20/getting-the-value-of-mask-parameters/


% Set each parameter value on the System object instance,
% including inactive properties
maskObject = getBlockMaskObject(blkHndl);

% Save off last warning state so that it can be restored.
% - Even when warnings are turned off, the last warning state
%   will still update.
% - See g2343250.
[lastmsg,lastid] = lastwarn;

% Suppress warnings about setting inactive system object
% properties
warnState = warning('off','MATLAB:system:nonRelevantProperty');
C = onCleanup(@()cleanUpWarning(warnState, lastmsg, lastid));

% Get resolved/evaluated values from the block.
maskParams = get_param(blkHndl,'MaskWSVariables');

for param = maskObject.Parameters
    if strcmp(param.ReadOnly, 'off')
        paramName = param.Name;
        paramVal = maskParams(arrayfun(@(x)strcmpi(x.Name,paramName),maskParams)).Value;
        if isa(paramVal,'Simulink.Parameter')
            paramVal = paramVal.Value;
        end
        if strcmp(paramName,'SimulateUsing')
            continue
        end
        if strcmp(param.Type, 'checkbox') || isa(param.DialogControl,'Simulink.dialog.parameter.CheckBox')
            paramVal = strcmp(paramVal, 'on');
        end
        sysObj.(paramName) = paramVal;
    end
end

end

function cleanUpWarning(warnState, lastmsg, lastid)
warning(warnState);
% Restore the last warning state
lastwarn(lastmsg,lastid);
end

function maskObject = getBlockMaskObject(hBlock)
% Returns system block's mask object from the system block's handle
% See also: matlab.system.ui.SimulinkDescriptor/getBlockActionSystemObjectInstance

maskObject = Simulink.Mask.get(hBlock);

% Use base mask if it exists to handle masked System block
% (g1247010).  While masks may recurse arbitrarily, the System
% object dialog can only be shown under a single top level mask.
if ~isempty(maskObject.BaseMask)
    maskObject = maskObject.BaseMask;
end
end