% WorkerMJSAccess - MJSAccess for use by worker MATLAB.

% Copyright 2020 The MathWorks, Inc.

classdef (Sealed, Hidden) WorkerMJSAccess < parallel.internal.cluster.ForwardingMJSAccess
    
    properties (SetAccess = immutable)
        % Username for the job/task this worker is running
        Username
    end
    
    methods (Access = private)
        function obj = WorkerMJSAccess(access, username)
            obj@parallel.internal.cluster.ForwardingMJSAccess(access);
            obj.Username = username;
        end
    end
        
    methods (Static)
        function clientAccess = create(access, cachedData, username)            
            cachedAccess = parallel.internal.cluster.CachedMJSAccess(access);
            cachedAccess.cacheWorkUnitProperties(cachedData.jobID, cachedData.jobProperties);
            cachedAccess.cacheWorkUnitProperties(cachedData.taskID, cachedData.taskProperties);
            cachedAccess.cacheClusterProperties(cachedData.clusterProperties);            
            clientAccess = parallel.internal.cluster.WorkerMJSAccess(cachedAccess, username);
        end
    end
    
    % Overwrite certain parallel.internal.cluster.IMJSAccess methods to
    % avoid worker making extra remote calls
    methods
        function checkCredentialsOfExistingUser(obj, username, hashedCredentials)
            if strcmp(username, obj.Username)
                return
            end
            obj.Access.checkCredentialsOfExistingUser(username, hashedCredentials);
        end
        
        function userExists = userExists(obj, username)
            if strcmp(username, obj.Username)
                userExists = true;
            else
                userExists = obj.Access.userExists(username);
            end
        end
    end
end

