% MJSClientSession - Holds all state required to represent an MJS client session

% Copyright 2020 The MathWorks, Inc.

classdef MJSClientSession < handle

    properties (SetAccess = immutable, GetAccess = private)
        Access
    end

    properties (SetAccess = private)
        % The MATLAB listener object associated with this session
        MJSEventListener

        % Unique ID for this client session
        ClientSessionID
    end

    methods
        function close(obj)
            obj.Access.closeClientSession(obj.ClientSessionID);
            obj.MJSEventListener.delete();
            obj.ClientSessionID = '';
        end

        function delete(obj)
            try
                obj.close();
            catch E
                % Catch exceptions on object deletion. Failing to close the
                % session on cleanup is not fatal, so we just log the error
                % and continue. See g2379903.
                dctSchedulerMessage(1, 'Failed to close client session.', E);
            end
        end
    end

    methods (Access = private)
        function obj = MJSClientSession(access, clientSessionID, listener)
            obj.Access = access;
            obj.ClientSessionID = clientSessionID;
            obj.MJSEventListener = listener;
        end
    end

    methods (Static)
        function session = create(access, callback)
            listener = access.createMJSEventListener(callback);
            clientSessionID = access.createClientSession();

            dctSchedulerMessage(2, 'Created a new client session with ID: %s', clientSessionID);
            session = parallel.internal.cluster.MJSClientSession(access, clientSessionID, listener);
        end
    end
end
