% Static helper class for creating and initialising MJSSupportWrapper for
% compute cloud client

%   Copyright 2020 The MathWorks, Inc.

classdef MJSComputeCloudSupportWrapperProvider
    
    methods (Static)
        function support = createSupport(getClusterDetailsFcn, promptForPassword, username)
            clusterDetails = getClusterDetailsFcn();

            % Before attempting to use the cluster, issue a
            % 'AssociateIPAddress' call to Cloud Center. Such a call is
            % only permitted if the cluster is online. This ensures the
            % client can use a cluster even if the IP address of the
            % machine it is running on has not been previously added to the
            % cluster's security group.
            currentClusterState = parallel.internal.types.CloudCenterClusterState.fromName(...
                                  clusterDetails.ClusterState);
            if (currentClusterState == parallel.internal.types.CloudCenterClusterState.Ready)
                try
                    parallel.internal.cloud.associateIPAddress(clusterDetails.ClusterID);
                catch E
                    associationErr = MException(message('parallel:cloud:AssociatingIPWithClusterFailed', E.message));
                    throw(associationErr);
                end
            end
            
            % We now have a cluster with a headnode, so we have a host and
            % name we can use to create a job manager access object.
            [host, name] = parallel.cluster.MJSCloudCluster.hGetHostAndName(clusterDetails, false);
            support = parallel.internal.cluster.MJSSupportWrapperProvider.createClientSupport(...
                host, name, promptForPassword, username);
        end
    end
end
