%

% Copyright 2018 The MathWorks, Inc.

function codeTrFile = checkCodeCompile(modelName, simMode)

% Default output
codeTrFile = '';

persistent isRequiredProductInstalled;
if isempty(isRequiredProductInstalled)
    isRequiredProductInstalled = license('test', 'RTW_Embedded_Coder');
end
if ~isRequiredProductInstalled
    return
end

% Check the input arguments
narginchk(2,2);
validateattributes(modelName, {'char', 'string'}, {'scalartext', 'nonempty'})
modelName = char(modelName);
simMode = validatestring(simMode, slcoverage.Selector.SupportedXILModes);

% The modes to tests
if strcmpi(simMode, 'sil')
    simModes = {'SIL'};
    simMode = SlCov.Utils.SIM_SIL_MODE_STR;
elseif strcmpi(simMode, 'pil')
    simModes = {'PIL'};
    simMode = SlCov.Utils.SIM_PIL_MODE_STR;
elseif strcmpi(simMode, 'xil')
    simModes = {'SIL', 'PIL'};
    simMode = SlCov.Utils.SIM_SIL_MODE_STR;
elseif strcmpi(simMode, 'modelrefsil')
    simModes = {'ModelRefSIL'};
    simMode = [];
elseif strcmpi(simMode, 'modelrefpil')
    simModes = {'ModelRefPIL'};
    simMode = [];
elseif strcmpi(simMode, 'modelrefxil')
    simModes = {'ModelRefSIL', 'ModelRefPIL'};
    simMode = [];
end
dbFiles = cell(1, numel(simModes));

% Find existing code traceability data base
for ii = 1:numel(simModes)
    moduleName = SlCov.coder.EmbeddedCoder.buildModuleName(modelName, simModes{ii});
    dbFiles{ii} = SlCov.coder.EmbeddedCoder.getResultsFile(moduleName);
    if isfile(dbFiles{ii})
        codeTrFile = dbFiles{ii};
        return
    end
end

% No existing file then force the generation but only if the current
% system target file is an Embedded Coder target and the simulation mode is
% not empty (model reference cannot be simulated without a caller model)
if get_param(modelName, 'IsERTTarget')~="on" || isempty(simMode)
    return
end
try
    cmd = sprintf('cvsim(''%s'', ''SimulationMode'', ''%s'', ''StopTime'', ''0'')',...
        modelName, simMode);
    evalc(cmd);
catch
    return
end

if isfile(dbFiles{1})
    codeTrFile = dbFiles{1};
end

