function state = getWorkUnitStateEnum( workUnit )
% Internal function that takes a job/task and returns its StateEnum

%   Copyright 2014-2018 The MathWorks, Inc.

try
    state = workUnit.hGetProperty( 'StateEnum' );
catch E
    dctSchedulerMessage( 1, 'Failed to retrieve work unit states. Original error:\n%s', E.getReport() );
    
    % Iterate over the work units to determine which one(s) could not be found
    uniformOutput = numel( workUnit ) < 2; % Return a normal array if single work unit
    state = arrayfun( @iGetStateNoError, workUnit, 'UniformOutput', uniformOutput )';
end
end

function state = iGetStateNoError( workUnit )
    try
        state = workUnit.hGetProperty( 'StateEnum' );
    catch E
        if isequal( E.identifier, 'parallel:cluster:storage:WorkUnitNotFound' )
            state = parallel.internal.types.States.Destroyed; % The work unit has been destroyed
        else
            state = parallel.internal.types.States.Unavailable; % Default
        end
    end
end