classdef ActiveServices < handle
% ActiveServices Manage list of active in-MATLAB persistence services.
% Each service is a named singleton. ActiveService object itself is also a 
% singleton.

% Copyright 2020-2021 The MathWorks, Inc.

    properties
        Services     % Services active in the current MATLAB session.
    end
    
    methods(Static)
        
        function ap = getInstance()
        % getInstance Return this session's ActiveService object. Create the
        % ActiveService object if necessary.
            persistent singleton
            if isempty(singleton)
                singleton = mps.persistence.internal.ActiveServices();
            end
            ap = singleton;
        end
        
    end
    
    methods (Access = protected)
        
        function obj = ActiveServices()
        % ActiveServices Protected constructor. Called by getInstance().
            obj.Services = containers.Map(...
                    'KeyType','char','ValueType','any');           
        end

    end
    
    methods
        
        function tf = isActive(obj,name)
        % isActive Is the named service active in the current MATLAB session?
            tf = isKey(obj.Services,name);
        end
        
        function service = get(obj,name)
        % get Return the named Service singleton object, or [] if none exists.

            % Buried too deeply to provide a good error message. Callers
            % must signal error condition.
            service = [];
            if isKey(obj.Services,name)
                service = obj.Services(name);
            end
        end
        
        function tf = remove(obj,name)
        % remove Remove named service from active services list.
            tf = false;
            if isKey(obj.Services,name)
                remove(obj.Services,name);
                tf = true;
            end
        end
        
        function tf = put(obj,name,service)
        % put Record named service on active services list.
            tf = false;
            if ~isKey(obj.Services,name)
                obj.Services(name) = service;
                tf = true;
            end
        end
    end
end

