using System.Globalization;
using System.IO;
using Chronos.App.Archiving;
using Chronos.App.Infrastructure;
using Chronos.App.Jobs;
using Chronos.App.Workspace;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
using Chronos.Data.Workspaces;
using Chronos.Testing;
namespace Chronos.App.Tests.Workspace;
///
/// The desktop's side of the workspace clean-up (phase 5c, P4): the workspace-clean and workspace-trash steps
/// run by a Cleanup job with no archive, the project open in Edit kept, a removal refused (its renders queued to be sent)
/// while renders wait, and the trash emptied only as planned, once its number of entries is typed.
///
[Category("workspace")]
public sealed class WorkspaceCleanupHostTests(TestContext context)
{
static WorkspaceCleanupHostTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
private static readonly TimeSpan Day = TimeSpan.FromDays(1);
[Test]
public async Task TheScheduledCleanUpRunsWithoutAnArchiveAndKeepsTheProjectOpenInEdit()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var settings = new AppSettings { WorkspaceAutoSync = false, WorkspaceCleanAfterDays = 30 };
var host = bed.Host(settings);
var mainId = await bed.CheckoutAsync(host);
settings.WorkspaceOpened[mainId] = DateTimeOffset.UtcNow - 40 * Day;
var project = host.Store.Find(mainId)!;
Assert.True(Directory.Exists(project.ProxiesDirectory), "copied");
// Open in Edit: kept, with why.
Guid? open = mainId;
host.OpenProject = () => open;
var kept = Assert.NotNull(await host.CleanAsync(cleanAfter: true));
Assert.Empty(kept.Cleaned);
Assert.True(kept.Kept is [{ Reason: WorkspaceKeep.Open }], "kept while open");
Assert.Equal("open in Edit", WorkspaceCleanStep.Reason(WorkspaceKeep.Open));
Assert.True(Directory.Exists(project.ProxiesDirectory), "the media stay");
// The schedule's Cleanup job, with no archive: the media go, the trash is only reported.
open = null;
await using var jobs = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(bed.Directory, "jobs.db")), bed.Ct);
var service = new ArchiveService(jobs, new ArchiveServiceOptions { CleanupSteps = [new WorkspaceCleanStep(() => host), new WorkspaceTrashStep(() => host)] });
await using var engine = new JobEngine(jobs, service.CreateJobHandlers(), new JobEngineOptions { WorkerId = "cleanup", PollInterval = TimeSpan.FromMilliseconds(50) });
await engine.StartAsync(bed.Ct);
var job = await engine.EnqueueAsync(ArchiveJobs.Cleanup(null, [WorkspaceCleanStep.StepName, WorkspaceTrashStep.StepName], 0), cancellationToken: bed.Ct);
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(60));
while ((await jobs.Jobs.GetAsync(job.Id, bed.Ct))!.State is JobState.Queued or JobState.Running)
{
Assert.True(DateTime.UtcNow < deadline, "the clean-up job did not finish");
await Task.Delay(50, bed.Ct);
}
var done = (await jobs.Jobs.GetAsync(job.Id, bed.Ct))!;
Assert.Equal(JobState.Done, done.State, done.Error ?? done.LogTail);
Assert.Contains("Workspace: projects cleaned: 1", done.LogTail);
Assert.Contains(Loc.L("Jobs.Log.WorkspaceTrash", Formatting.Count(0), Formatting.Bytes(0)), done.LogTail);
Assert.False(Directory.Exists(project.ProxiesDirectory), "the media went");
Assert.True(host.Store.Find(mainId) is not null && File.Exists(project.BundlePath), "the copy and its work stay");
Assert.False((await host.FindAsync(mainId))!.HasMedia, "opening it copies the media again");
}
[Test]
public async Task RendersNotSentBlockTheRemovalAndAreQueuedToBeSent()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
var mainId = await bed.CheckoutAsync(host);
var project = host.Store.Find(mainId)!;
Directory.CreateDirectory(project.ExportsDirectory);
File.WriteAllText(project.ExportFile("clip.mp4"), "rendered");
project.WriteRenders(WorkspaceRenders.Empty.With(new WorkspaceRenderEntry(Guid.CreateVersion7(), Guid.CreateVersion7(), "clip.mp4", new string('a', 64), 8,
"preset", "h264", 1920, 1080, 25, 4, mainId, null, null, DateTimeOffset.UtcNow, WorkspaceRenderEntry.Pending, null)));
var plan = await host.PlanRemovalAsync(mainId);
Assert.True(plan is { UnsentRenders: 1, IsSafe: false }, "a render waits");
var dialog = new RemoveCopyDialogViewModel(plan, _ => Task.CompletedTask, () => Task.CompletedTask, () => true, _ => { });
Assert.Contains(dialog.Facts, f => f.Label == Loc.L("Editor.RemoveCopy.UnsentRenders") && f.Value == Formatting.Count(1));
Assert.False(dialog.RemoveCommand.CanExecute(null), "not while renders wait");
var refused = await Assert.ThrowsAsync(() => host.RemoveLocalCopyAsync(mainId, discard: false));
Assert.Equal(Loc.L("Errors.Workspace.UnsentRenders"), refused.Message);
Assert.NotNull(host.Store.Find(mainId), "nothing was removed");
var sends = (await bed.Db.Jobs.ListAsync(null, JobKind.WorkspaceSend, cancellationToken: bed.Ct)).Items;
var send = Assert.Contains(sends, j => j.TargetIds.Contains(bed.SequenceId));
Assert.Equal(mainId, WorkspaceJobs.SendParameters(send)!.ProjectId);
}
[Test]
public async Task TheTrashIsEmptiedAsPlannedOnceItsNumberIsTyped()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 2);
var host = bed.Host();
Assert.True((await host.PlanTrashAsync()).IsEmpty, "no trash yet");
var folder = WorkspaceTrash.FolderOf(host.Root);
foreach (var name in new[] { "a", "b" })
{
var entry = Directory.CreateDirectory(Path.Combine(folder, Guid.CreateVersion7().ToString("N") + "-" + DateTime.UtcNow.Ticks)).FullName;
File.WriteAllText(Path.Combine(entry, name + ".txt"), "kept aside " + name);
}
var usage = await host.UsageAsync();
Assert.Equal(2L * "kept aside a".Length, usage.TrashBytes);
var plan = await host.PlanTrashAsync();
Assert.Equal((2, 2L * "kept aside a".Length), (plan.Items.Count, plan.Bytes));
var closed = 0;
WorkspaceTrashResult? emptied = null;
var dialog = new WorkspaceTrashDialogViewModel(plan, p => host.EmptyTrashAsync(p), r => emptied = r, _ => closed++);
Assert.Equal(2, dialog.Rows.Count);
Assert.Equal("2", dialog.Confirmation);
Assert.False(dialog.EraseCommand.CanExecute(null), "nothing typed");
dialog.Typed = "3";
Assert.False(dialog.CanErase, "the wrong number");
dialog.Typed = " 2 ";
Assert.True(dialog.CanErase && dialog.EraseCommand.CanExecute(null), "the number of entries");
// An entry added since the plan: refused, nothing erased, the dialog stays open with why.
var late = Directory.CreateDirectory(Path.Combine(folder, Guid.CreateVersion7().ToString("N") + "-" + DateTime.UtcNow.Ticks)).FullName;
File.WriteAllText(Path.Combine(late, "late.txt"), "late");
dialog.EraseCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => dialog.ErrorText is { Length: > 0 }, "the emptying is refused");
Assert.Equal(0, closed);
Assert.Equal(3, (await host.PlanTrashAsync()).Items.Count);
// As planned again: erased for good, the dialog closed.
plan = await host.PlanTrashAsync();
dialog = new WorkspaceTrashDialogViewModel(plan, p => host.EmptyTrashAsync(p), r => emptied = r, _ => closed++) { Typed = "3" };
dialog.EraseCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => closed == 1, "the dialog closes");
Assert.True(emptied is { Items: 3 }, "three entries erased");
Assert.True((await host.PlanTrashAsync()).IsEmpty, "the trash is empty");
// An empty trash offers nothing to erase.
var none = new WorkspaceTrashDialogViewModel(await host.PlanTrashAsync(), p => host.EmptyTrashAsync(p), null, _ => { }) { Typed = "0" };
Assert.False(none.CanErase);
Assert.Equal(Loc.L("Tooltips.Settings.Workspace.EmptyTrash.Disabled"), none.EraseToolTip);
}
}