using System.IO;
using System.Windows.Input;
using System.Windows.Threading;
using Chronos.App.Infrastructure;
using Chronos.App.Settings;
using Chronos.Core.Conversion;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Archiving;
///
/// Convert… (owner review 2, R7; BRIEF §12.2, §12.5): the photos of a set of sequences, or of every sequence of the archive,
/// converted to JPEG, 16-bit TIFF or linear DNG. The format starts on the archival one ()
/// and the JPEG quality on ; the mode starts unchosen, so every run says whether
/// the converted files replace the photos (the originals go to the archive's trash) or go into new sequences (the originals
/// stay as they are). The dry run (the engine's plan, nothing changes on disk) follows the choices and lists each sequence
/// with what converts and what stays as it is, a summary and the free space line. Apply asks to type the number of photos a
/// Replace replaces, then queues the conversion job of exactly that plan (): resumable,
/// paused and followed in Jobs; a sequence changed after the dry run is left as it is.
///
public sealed class ConvertDialogViewModel : ArchiveDialogViewModel
{
private readonly ArchiveService _archives;
private readonly Core.Model.Archive _archive;
private readonly IReadOnlyList? _set;
private readonly Func _enqueue;
private readonly Func _confirm;
private readonly DispatcherTimer _delay = new() { Interval = TimeSpan.FromMilliseconds(400) };
/// Guards and : only the latest dry run started ever publishes its result.
private readonly Lock _gate = new();
private DryRun _run = new(null);
private CancellationTokenSource? _planning;
private ConvertTarget _target = ConvertOptions.ArchivalTarget;
private ConvertMode? _mode;
/// The sequences to convert; null for every sequence of .
/// Queues the conversion job and says so.
/// Asks the typed confirmation of a Replace; true when the user typed it and chose Replace.
public ConvertDialogViewModel(ArchiveService archives, Core.Model.Archive archive, IReadOnlyList? set, Func enqueue,
Func confirm, Action close)
: base(close)
{
ArgumentNullException.ThrowIfNull(archive);
_archives = archives;
_archive = archive;
_set = set;
_enqueue = enqueue;
_confirm = confirm;
// Only a JPEG has a quality: for the other formats the field neither counts nor blocks.
Quality = new EditableField(ConvertOptions.DefaultQuality.ToString(Loc.Culture), t => _target == ConvertTarget.Jpeg ? ConvertPlans.ValidateQuality(t) : null,
_ => OnCommitted(), () => Loc.L("Tooltips.Archive.ConvertQuality"));
Quality.PropertyChanged += (_, e) =>
{
if (e.PropertyName == nameof(EditableField.Text)) OnTyped();
};
_delay.Tick += (_, _) => _ = PlanAsync();
ApplyCommand = new AsyncRelayCommand(ApplyAsync, () => ApplyBlocker is null);
}
/// "Convert 36 sequences", or "Convert ChronosArchive" for every sequence.
public string Heading => _set is null ? Loc.L("Archive.Convert.HeadingAll", _archive.Name) : Loc.Plural("Archive.Convert.Heading", _set.Count);
/// The format the converted files have; a change plans again.
public ConvertTarget Target
{
get => _target;
set
{
if (!Enum.IsDefined(value) || !Set(ref _target, value)) return;
// The quality's problem counts for a JPEG only.
Quality.Refresh();
OnPropertyChanged(nameof(IsJpeg));
OnPropertyChanged(nameof(IsTiff16));
OnPropertyChanged(nameof(IsLinearDng));
OnPropertyChanged(nameof(IsQualityEnabled));
_ = PlanAsync();
}
}
public bool IsJpeg
{
get => _target == ConvertTarget.Jpeg;
set
{
if (value) Target = ConvertTarget.Jpeg;
}
}
public bool IsTiff16
{
get => _target == ConvertTarget.Tiff16;
set
{
if (value) Target = ConvertTarget.Tiff16;
}
}
public bool IsLinearDng
{
get => _target == ConvertTarget.LinearDng;
set
{
if (value) Target = ConvertTarget.LinearDng;
}
}
/// The JPEG quality, 1–100; typing plans again once it pauses, Enter at once.
public EditableField Quality { get; }
public bool IsQualityEnabled => _target == ConvertTarget.Jpeg;
/// What becomes of the originals, chosen at every run; null until the user picks one, and Apply waits for it.
public ConvertMode? Mode
{
get => _mode;
set
{
if (value is { } mode && !Enum.IsDefined(mode)) return;
if (!Set(ref _mode, value)) return;
// The rows say what becomes of the photos skipped in the mode's words: not copied into a new sequence.
lock (_gate)
{
if (_run.Plan is { } plan) _run = _run with { Rows = RowsOf(plan) };
}
OnPropertyChanged(nameof(IsReplace));
OnPropertyChanged(nameof(IsNewSequence));
OnPlanChanged();
}
}
public bool IsReplace
{
get => _mode == ConvertMode.Replace;
set
{
if (value) Mode = ConvertMode.Replace;
}
}
public bool IsNewSequence
{
get => _mode == ConvertMode.NewSequence;
set
{
if (value) Mode = ConvertMode.NewSequence;
}
}
/// The last dry run, one row per sequence that converts or keeps photos as they are, in the order the job takes them.
public IReadOnlyList Rows => _run.Rows ?? [];
///
/// The plan of the options on screen, in the mode chosen (as planned while none is); null while it is made, when it
/// failed, or once the options changed. The mode does not change what converts, so choosing it plans nothing again.
///
public ConvertPlan? Plan => _run is { Plan: { } plan } run && run.For is { } options && options == Current()
? _mode is { } mode ? plan with { Mode = mode } : plan
: null;
public string SummaryText => Plan is { } plan ? ConvertPlans.Summary(plan) : string.Empty;
/// The free space line of a dry run that converts something; null otherwise.
public string? SpaceText => Plan is { Frames: > 0 } plan ? ConvertPlans.Space(plan.Space).Text : null;
/// The archive's volume lacks the space the conversion needs: the line is a warning and Apply waits.
public bool IsSpaceShort => Plan is { Frames: > 0 } plan && !plan.Space.Enough;
/// The space line shows and says nothing is missing (or that the free space cannot be measured).
public bool IsSpaceFine => Plan is { Frames: > 0 } plan && plan.Space.Enough;
/// Asks the typed confirmation of a Replace, then queues the job of the plan on screen and closes.
public ICommand ApplyCommand { get; }
public string ApplyToolTip => ApplyBlocker
?? Loc.L(_mode == ConvertMode.Replace ? "Tooltips.Archive.ConvertApplyReplace" : "Tooltips.Archive.ConvertApplyNew");
/// Why Apply is disabled; null when it can run. The mode is asked last: first whether there is anything to convert.
private string? ApplyBlocker
{
get
{
if (IsBusy) return Loc.L("Archive.Blocked.Applying");
if (Quality.Error is { } quality) return quality;
var run = _run;
if (run.For is null || run.For != Current()) return Loc.L("Archive.Blocked.Planning");
if (run.Plan is not { } plan) return run.Error ?? Loc.L("Archive.Blocked.Planning");
if (plan.Frames == 0) return Loc.L("Archive.Blocked.NothingToConvert");
if (!plan.Space.Enough) return ConvertPlans.Space(plan.Space).Text;
return _mode is null ? Loc.L("Archive.Blocked.NoMode") : null;
}
}
/// The format and quality on screen, as the engine takes them; null while the quality of a JPEG cannot be used.
public ConvertOptions? Current()
{
if (Quality.Error is not null) return null;
return new ConvertOptions(_target, _target == ConvertTarget.Jpeg ? ConvertPlans.ParseQuality(Quality.Text) : ConvertOptions.DefaultQuality);
}
///
/// The dry run of the options on screen; it clears the last failure and stands in for one still waiting on typing.
///
public Task PlanAsync()
{
_delay.Stop();
ClearError();
return DryRunAsync();
}
/// Shows a dry run made elsewhere (capture) as the one of the options on screen.
public void Show(ConvertPlan plan)
{
ArgumentNullException.ThrowIfNull(plan);
_delay.Stop();
lock (_gate)
{
_planning?.Cancel();
_planning = null;
_run = new DryRun(Current(), plan, RowsOf(plan));
}
BusyText = null;
ClearError();
OnPlanChanged();
}
public override void Dispose()
{
_delay.Stop();
lock (_gate) _planning?.Cancel();
base.Dispose();
}
/// The rows, the quality's message, the summary and the space line in the new language.
protected override void OnLanguageChanged()
{
Quality.Refresh();
lock (_gate)
{
if (_run.Plan is { } plan) _run = _run with { Rows = RowsOf(plan) };
}
base.OnLanguageChanged();
}
/// The rows of in the mode chosen (as planned while none is: the skipped photos stay as they are).
private IReadOnlyList RowsOf(ConvertPlan plan) => ConvertPlans.Rows(_mode is { } mode ? plan with { Mode = mode } : plan);
/// Typing makes the dry run on screen old at once (Apply waits) and plans again once the typing pauses.
private void OnTyped()
{
OnPlanChanged();
_delay.Stop();
_delay.Start();
}
///
/// Enter, or the focus leaving the quality, plans at once, unless the dry run on screen or the one under way is already of
/// these options: a click on Apply takes the focus from the field first, and an identical dry run started then would turn
/// Apply off under the click.
///
private void OnCommitted()
{
if (IsPlanned()) _delay.Stop();
else _ = PlanAsync();
}
/// The options on screen have their plan, or a dry run of them is under way; false after a failed one.
private bool IsPlanned()
{
lock (_gate) return _run.For is { } options && options == Current() && (_run.Plan is not null || _planning is not null);
}
private async Task DryRunAsync()
{
var options = Current();
var cts = options is null ? null : new CancellationTokenSource();
lock (_gate)
{
_planning?.Cancel();
_planning = cts;
_run = new DryRun(options);
}
BusyText = cts is null ? null : Loc.L("Archive.Reorganize.Planning");
OnPlanChanged();
if (cts is null) return;
var set = _set;
// What converts is the same in either mode: the plan made with one serves the other (Plan).
var mode = _mode ?? ConvertMode.Replace;
DryRun result;
Exception? failure = null;
try
{
var plan = await Task.Run(() => _archives.PlanConvertAsync(_archive.Id, set, options!, mode, cts.Token), cts.Token);
// In the mode chosen now: it may have been chosen while the plan was made.
result = new DryRun(options, plan, RowsOf(plan));
}
catch (OperationCanceledException) when (cts.IsCancellationRequested)
{
// A newer dry run took its place, or the dialog closed.
result = new DryRun(options);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or InvalidDataException or DatabaseException)
{
Log.Warning("archive", "Conversion dry run failed", ex);
failure = ex;
result = new DryRun(options, Error: ArchiveFailures.Cause(ex));
}
bool latest;
lock (_gate)
{
latest = ReferenceEquals(_planning, cts);
if (latest)
{
_planning = null;
_run = result;
}
}
cts.Dispose();
if (!latest) return;
BusyText = null;
if (failure is not null) ShowError(failure);
OnPlanChanged();
}
private void OnPlanChanged()
{
OnPropertyChanged(nameof(Rows));
OnPropertyChanged(nameof(Plan));
OnPropertyChanged(nameof(SummaryText));
OnPropertyChanged(nameof(SpaceText));
OnPropertyChanged(nameof(IsSpaceShort));
OnPropertyChanged(nameof(IsSpaceFine));
OnPropertyChanged(nameof(ApplyToolTip));
CommandManager.InvalidateRequerySuggested();
}
private async Task ApplyAsync()
{
if (ApplyBlocker is not null || Plan is not { } plan || _mode is not { } mode) return;
ClearError();
// Replace changes the photos of the archive: the number of photos it replaces is typed first.
if (mode == ConvertMode.Replace && (ConvertPlans.ReplaceRequest(plan) is not { } request || !_confirm(request))) return;
IsBusy = true;
try
{
await _enqueue(ArchiveJobs.Convert(_archive, plan));
Log.Info("archive", $"Conversion of {plan.Frames} photo(s) in {plan.Converted.Count()} sequence(s) of {_archive.RootPath} to {plan.Options.Target} ({mode}) queued");
}
catch (DatabaseException ex)
{
Log.Warning("archive", "The conversion was not queued", ex);
ShowError(ex);
return;
}
finally
{
IsBusy = false;
}
Close();
}
/// A dry run: the options it is for and, once it ended, its plan and rows, or why it failed.
private sealed record DryRun(ConvertOptions? For, ConvertPlan? Plan = null, IReadOnlyList? Rows = null, string? Error = null);
}