using Titano.Core.Model;
namespace Titano.App.Editor;
///
/// The analyses and renders of the open sequence that wait, run or are paused, as the source reports them (BRIEF §12.3
/// "while a job runs on this sequence, settings are disabled", §11.5): the editor's busy lock, whether Analyse would
/// queue a second analysis, and the server job the header of a server sequence shows. Call from one thread.
///
public sealed class SequenceJobs(Guid sequenceId)
{
private readonly Dictionary _active = [];
/// An analysis or render runs: settings wait.
public bool IsBusy => _active.Values.Any(j => j.State == JobState.Running);
/// A deep analysis waits, runs or is paused.
public bool IsAnalysing => _active.Values.Any(j => j.Kind == JobKind.DeepAnalyse);
/// The job to show: one running, else one paused, else the oldest waiting; null when there is none.
public Job? Shown => _active.Values
.OrderBy(j => j.State switch { JobState.Running => 0, JobState.Paused => 1, _ => 2 })
.ThenBy(j => j.Started ?? j.Created)
.FirstOrDefault();
/// An analysis or render of this sequence.
public bool Concerns(Job job)
{
ArgumentNullException.ThrowIfNull(job);
return job.TargetIds.Contains(sequenceId) && job.Kind is JobKind.DeepAnalyse or JobKind.LightAnalyse or JobKind.Render;
}
/// The job is one of those that wait, run or are paused.
public bool IsActive(Guid jobId) => _active.ContainsKey(jobId);
/// Takes in a job's new state.
/// Whether a job joined or left the active ones or changed state; progress alone does not count.
public bool Track(Job job)
{
if (!Concerns(job)) return false;
if (job.State is not (JobState.Queued or JobState.Running or JobState.Paused)) return _active.Remove(job.Id);
var changed = !_active.TryGetValue(job.Id, out var known) || known.State != job.State;
_active[job.Id] = job;
return changed;
}
}