function [profNames, schedCompNames, projCompNames, profNamesInFile] = importProfileOrConfiguration(filename, loadProfile)
% importProfileOrConfiguration - import a profile or configuration from file
% Always returns profile and component names in cell arrays.

% Copyright 2011-2020 The MathWorks, Inc.

validateattributes(filename, {'char'}, {'row'});
if nargin < 2
    loadProfile = true;
else
    validateattributes(loadProfile, {'logical'}, {'scalar'});
end

% Check that the file is not a directory
if exist(filename, 'dir')
    error(message('parallel:settings:ImportProfileFailedToImportFolder', filename));
end

% Check that the file exists
if exist(filename, 'file') ~= 2
    error(message('parallel:settings:ImportProfileInvalidFilename', ...
        filename));
end

if loadProfile
    [profNames, schedCompNames, projCompNames, profNamesInFile] = ...
        iLoadSettings(filename);
else
    [profNames, schedCompNames, projCompNames, profNamesInFile] = ...
        iLoadConfigurationsMat(filename);
end


%-----------------------------------------------
function [profNames, schedCompNames, projCompNames, profNamesInFile] = ...
    iLoadSettings(filename)
p = parallel.Settings;
[profNames, schedCompNames, projCompNames, profNamesInFile] = p.hImportProfilesFromFile(filename);

%-----------------------------------------------
function [profNames, schedCompNames, projCompNames, profNamesInFile] = ...
    iLoadConfigurationsMat(filename)
import parallel.internal.settings.ConfigurationsHelper;

[~, undoc] = pctconfig();
if undoc.useprofiles
    ser = ConfigurationsHelper.getCurrentSerializer();
    try
        [profileName, nameInFile] = ser.createNewFromFile(filename);
    catch err
        rethrow(err);
    end
    p = parallel.Settings();
    profile = p.findProfile('Name', profileName);
    profNames = {profileName};
    schedCompNames = {profile.SchedulerComponent};
    projCompNames = {profile.ProjectComponent};
    profNamesInFile = {nameInFile};
    
    if ~p.hIsValidName(nameInFile)
        warning(message('parallel:settings:ImportConfigurationNameChangedNotVarName', ...
                        nameInFile, profileName, nameInFile));
    end
else
    error(message('parallel:settings:ImportConfigurationButNotUsingProfiles', filename));
end
