% Helper class to manage:
% - checking whether a profile/config exists
% - building a scheduler/cluster on the basis of a Profile/Configuration

% Copyright 2011-2020 The MathWorks, Inc.

classdef (Hidden, Sealed) ProfileConfigHelper < handle
    properties ( GetAccess = private, SetAccess = immutable )
        ListNamesFcn
        GetDefaultNameFcn
        BuildSchedFcn
        ThrowNoSuchConfigFcn
    end
    properties ( SetAccess = immutable )
        PropertyName % Either 'profile' or 'configuration'.
    end

    methods ( Access = private )
        function obj = ProfileConfigHelper()
        % Build a ProfileConfigHelper for API-2.
            obj.ListNamesFcn         = @iGetAllProfiles;
            obj.GetDefaultNameFcn    = @iGetDefaultProfile;
            obj.BuildSchedFcn        = @parcluster;
            obj.PropertyName         = 'profile';
            obj.ThrowNoSuchConfigFcn = @iNoSuchProfile;
        end
    end
    methods ( Static )
        function pch = buildDefault()
            import parallel.internal.apishared.ProfileConfigHelper
            pch = ProfileConfigHelper.buildApi2();
        end
        function pch = buildApi2()
            persistent HELPER
            if isempty( HELPER )
                HELPER = parallel.internal.apishared.ProfileConfigHelper();
            end
            pch = HELPER;
        end
    end
    methods
        function names = getAllNames( obj )
            names = obj.ListNamesFcn();
        end
        function default = getDefaultName( obj )
            default = obj.GetDefaultNameFcn();
        end
        function sched = buildScheduler( obj, name )
            sched = obj.BuildSchedFcn( name );
        end
        function sched = buildDefaultScheduler( obj )
            sched = obj.buildScheduler( obj.getDefaultName() );
        end
        function tf = nameExists( obj, name )
        % Call this to check that a profile/configuration name exists. The
        % caller should have already checked that 'name' is a string.
            validateattributes( name, {'char'}, {} );
            tf = ismember( name, obj.getAllNames() );
        end
        function throwNoSuchConfig( obj, name )
            obj.ThrowNoSuchConfigFcn( name )
        end
    end
end


% --------------------------------------------------------------------------
function iNoSuchProfile( name )
    s = parallel.Settings;
    s.hThrowNonExistentProfile( name );
end

% --------------------------------------------------------------------------
function names = iGetAllProfiles()
    s = parallel.Settings;
    names = s.hGetAllProfileNames();
end

% --------------------------------------------------------------------------
function default = iGetDefaultProfile()
    s = parallel.Settings;
    default = s.DefaultProfile;
end
