using System.ComponentModel;
using System.Windows.Input;
using Titano.App.Editor;
using Titano.App.Infrastructure;
using Titano.App.Shell;
using Titano.Core.Diagnostics;
using Titano.Core.Export;
using Titano.Core.Imaging.Decoders;
using Titano.Core.Localization;
using Titano.Data.Archiving;
using Titano.Ui.Mvvm;
namespace Titano.App.Sections;
///
/// The Sequence section (BRIEF §12.3): opens the sequence the Library (or Jobs) chose into an
/// and closes the previous one after saving it; without a sequence it shows the empty state. A failed open is reported
/// and leaves the section usable; an edit that cannot be saved is never dropped without the user's confirmation.
///
public sealed class SequenceViewModel : SectionViewModel
{
private EditorViewModel? _editor;
private Guid? _openId;
private bool _isLoading;
private Task _switch = Task.CompletedTask;
public SequenceViewModel(ShellViewModel shell)
: base(SectionKey.Sequence, "Icon.Sequence")
{
Shell = shell;
OpenLibraryCommand = new RelayCommand(() => Shell.Navigate(SectionKey.Library));
shell.PropertyChanged += OnShellChanged;
}
public ShellViewModel Shell { get; }
public ICommand OpenLibraryCommand { get; }
/// The open sequence; null shows the empty state.
public EditorViewModel? Editor
{
get => _editor;
private set
{
if (!Set(ref _editor, value)) return;
OnPropertyChanged(nameof(IsEmpty));
OnPropertyChanged(nameof(Title));
}
}
public bool IsLoading { get => _isLoading; private set => Set(ref _isLoading, value); }
public bool IsEmpty => _editor is null && !_isLoading;
/// The open sequence has an edit not stored yet (the save follows each change after a moment, and retries after a failure).
public bool HasPendingSave => _editor?.Session.HasPendingSave == true;
/// "Titano — Harbour sunset" while a sequence is open.
public override string Title => _editor?.Title ?? Label;
/// Opens (the editor of another sequence is saved and closed first).
public Task OpenAsync(Guid sequenceId)
{
_switch = SwitchAsync(_switch, sequenceId);
return _switch;
}
///
/// Stores the open sequence's last edit. When the save fails (archive offline, read-only, busy), asks whether to
/// discard the edit (BRIEF §12.1: modals only for destructive confirmations).
///
/// True when the editor may close: everything is stored or the user chose to discard.
public async Task ConfirmCloseAsync()
{
if (Editor is not { } editor || await editor.Session.FlushAsync()) return true;
return Shell.Services.Dialogs.Confirm(new ConfirmRequest
{
Heading = Loc.L("Editor.Unsaved.Title"),
Message = Loc.L("Editor.Unsaved.Message", editor.Title, editor.Session.LastSaveError?.Message ?? string.Empty),
SafeText = Loc.L("Editor.Unsaved.Keep"),
SafeToolTip = Loc.L("Tooltips.Editor.Unsaved.Keep"),
ActionText = Loc.L("Editor.Unsaved.Discard"),
ActionToolTip = Loc.L("Tooltips.Editor.Unsaved.Discard"),
IsDestructive = true,
});
}
/// Closes the open sequence (after , which stores its last edit).
public async Task CloseAsync()
{
await Settled(_switch);
if (Editor is not { } editor) return;
Editor = null;
_openId = null;
await editor.DisposeAsync();
}
public override void Dispose()
{
Shell.PropertyChanged -= OnShellChanged;
Editor?.Dispose();
base.Dispose();
}
protected override void OnActivated()
{
if (Shell.CurrentSequenceId is { } id && id != _openId) _ = OpenAsync(id);
}
private void OnShellChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(ShellViewModel.CurrentSequenceId) && IsSelected) OnActivated();
}
/// Waits for ; its failure was reported where it happened.
private static async Task Settled(Task task)
{
try
{
await task;
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Debug("editor", $"An earlier open of the editor failed: {ex.Message}");
}
}
private async Task SwitchAsync(Task previous, Guid sequenceId)
{
await Settled(previous);
if (sequenceId == _openId) return;
// The open sequence keeps its editor while its last edit is neither stored nor deliberately discarded.
if (!await ConfirmCloseAsync()) return;
var services = Shell.Services;
IsLoading = true;
OnPropertyChanged(nameof(IsEmpty));
try
{
if (Editor is { } old)
{
Editor = null;
await old.DisposeAsync();
}
_openId = sequenceId;
if (services.Database is not { } db) throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"));
var processing = services.Processing?.Options;
var source = new LocalSequenceSource(db, sequenceId, processing?.Archive.Decoder ?? DecoderFactory.CreateClient(null), services.Engine,
processing?.Archive);
var content = await source.LoadAsync(CancellationToken.None);
var encoders = processing?.Encoders ?? [];
var session = new EditorSession(source, content, [.. encoders.SelectMany(e => e.Capabilities)]);
var editor = new EditorViewModel(Shell, session, encoders, processing?.Host ?? EncoderHost.Client);
Editor = editor;
await editor.AttachJobsAsync();
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
// Whatever failed (index, decoder set-up, advisor, the job list), the section stays usable: an editor that
// opened stays open, otherwise the next Open tries again.
if (Editor is null) _openId = null;
Log.Warning("editor", $"Sequence {sequenceId} could not be opened", ex);
Shell.ReportError(ex);
}
finally
{
IsLoading = false;
OnPropertyChanged(nameof(IsEmpty));
}
}
}