function state = deriveJobStateFromTasks( obj, job )
% deriveJobStateFromTasks - look at task states and compute the job state.

% Copyright 2011-2018 The MathWorks, Inc.

import parallel.internal.types.States

numPending   = 0;
numRunning  = 0;
numFinished = 0;
numFailed   = 0;

tasks = job.Tasks;

for ii = 1:numel( tasks )
    thisTask = tasks(ii);
    taskState = obj.hGetTaskStateEnum(thisTask);
    
    switch taskState
        case States.Pending
            numPending     = numPending   + 1;
        case States.Running
            numRunning     = numRunning  + 1;
        case States.Finished
            numFinished    = numFinished + 1;
        case States.Failed
            numFailed      = numFailed   + 1;
        otherwise
            warning(message('parallel:cluster:LocalUnexpectedTaskState', char( taskState )));
    end
end

if numPending > 0 && ~any( [ numRunning, numFinished, numFailed ] )
    state = States.Queued;
elseif any( [numPending, numRunning] )
    state = States.Running;
elseif numFailed == 0
    state = States.Finished;
else
    state = States.Failed;
end
end
