% Static helper class for creating and caching CredentialStore

%   Copyright 2020-2021 The MathWorks, Inc.

classdef CredentialStoreProvider
    
    methods (Static)
        % Available for tests to not use the existing store for a cluster
        % but get a new empty one
        function oldValue = setGetEnabled(newValue)
            mlock;
            persistent CACHE_ENABLED;
            if isempty(CACHE_ENABLED)
                CACHE_ENABLED = true;
            end
            oldValue = CACHE_ENABLED;

            if nargin < 1
                return
            end

            CACHE_ENABLED = newValue;
        end
        
        % Get existing credential store for given key or create a new one
        function store = getOrCreate(key)
            if ~parallel.internal.cluster.CredentialStoreProvider.setGetEnabled()
                dctSchedulerMessage(4, 'Credential store cache disabled');
                store = parallel.internal.cluster.CredentialStore.create(key);
                return
            end

            mlock;
            persistent CREDENTIAL_CACHE;
            if isempty(CREDENTIAL_CACHE)
                CREDENTIAL_CACHE = containers.Map();
            end

            % Getting cached value
            if isKey(CREDENTIAL_CACHE, key)
                dctSchedulerMessage(4, 'Found cached credential store for key: %s', key);
                store = CREDENTIAL_CACHE(key);
            else
                dctSchedulerMessage(4, 'Creating new credential store for key: %s', key);
                store = parallel.internal.cluster.CredentialStore.create(key);
                CREDENTIAL_CACHE(key) = store;
            end
        end
    end
end
