% ClientJmAccessFactory - generates the access classes for interactions
% with a ProxiedJobManagerClient from a client MATLAB

% Copyright 2014-2021 The MathWorks, Inc.

classdef (Hidden) ClientJmAccessFactory < parallel.internal.cluster.JmAccessFactory    
    properties (SetAccess = immutable, GetAccess = private)
        Username
        PromptForPassword
        Host
        Name
        Notifier = []
    end
    
    methods
        function obj = ClientJmAccessFactory(cache, host, name, username, promptForPassword, notifier)
            obj@parallel.internal.cluster.JmAccessFactory(cache);
            obj.Host = host;
            obj.Name = name;
            obj.Username = username;
            obj.PromptForPassword = promptForPassword;
            if nargin > 5
                obj.Notifier = notifier;
            end
        end
        
        function [jmAccess, accessCleanup] = getOrCreate(obj)
            jmProxy = parallel.internal.cluster.JobManagerFinder.getOneJobManagerProxyInterruptibly(...
                obj.Host, obj.Name, Inf);
            newJmAccess = com.mathworks.toolbox.distcomp.mjs.client.ProxiedJobManagerClient(jmProxy);
            newJmAccess.getCredentialConsumerFactory().setInteractive(obj.PromptForPassword);
            userIdentity = newJmAccess.promptForIdentity(obj.Username);
            [jmAccess, accessCleanup] = obj.initJmAccess(newJmAccess, ...
                {'Username',   'PromptForPassword'}, ...
                {userIdentity, obj.PromptForPassword });
        end
    end
    
    methods (Hidden)
        function hSetCredentialConsumerFactory(obj, consumerFactory)
            % Used by tests only
            obj.MJSAccess.setCredentialConsumerFactory(consumerFactory);
        end
        
        function hSetCurrentUser(obj, userIdentity)
            % Used by tests only
            obj.MJSAccess.setCurrentUser(userIdentity);
        end
    end
end
