using System.IO;
using System.Net;
using Chronos.App.Archiving;
using Chronos.App.Infrastructure;
using Chronos.App.Server;
using Chronos.App.Shell;
using Chronos.Core.Archiving;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Projects;
using Chronos.Data.Sync;
using Chronos.Data.Workspaces;
using Chronos.Protocol.Client;
using Chronos.Ui.Controls;
namespace Chronos.App.Workspace;
///
/// How the workspace's states, projects, versions and failures read in the UI (owner review 2, R8). WPF-free. A text that
/// names the project's home has a form for each: "the library" (this PC's archive) and, with server, "the server"
/// (phase 5b: its key with ).
///
public static class WorkspaceText
{
/// The suffix of a text's key in its form for a project whose home is a server.
public const string ServerSuffix = ".Server";
/// The project's name; the Main project in the UI language.
public static string ProjectName(string name, bool isMain) =>
isMain && string.Equals(name, ProjectService.MainName, StringComparison.Ordinal) ? Loc.L("Editor.Project.Main") : name;
///
/// The text of worded for the project's home: its server form () when
/// , the key itself for a text that names no home.
///
public static string ForHome(string key, bool server, params object?[] args)
{
ArgumentNullException.ThrowIfNull(key);
var worded = server && Loc.Get(key + ServerSuffix, Loc.Culture) is not null ? key + ServerSuffix : key;
return args.Length == 0 ? Loc.L(worded) : Loc.L(worded, args);
}
///
/// The state chip: "In sync", "Not sent", "Conflict"…; "Syncing" while a sync runs; worded for a server's project where
/// the state names the home ("Server newer", "Not on server").
///
public static string State(WorkspaceStatus? status, bool syncing = false, bool server = false) =>
syncing ? Loc.L("Editor.Workspace.State.Syncing")
: status is null ? Loc.L("Editor.Workspace.State.Reading")
: ForHome("Editor.Workspace.State." + status.State, server);
public static StatusKind Kind(WorkspaceStatus? status, bool syncing = false) => syncing ? StatusKind.Running : status?.State switch
{
WorkspaceState.InSync => StatusKind.Synced,
WorkspaceState.Modified or WorkspaceState.Ahead => StatusKind.Queued,
WorkspaceState.Behind => StatusKind.Remote,
WorkspaceState.Conflict => StatusKind.Error,
WorkspaceState.Offline => StatusKind.Offline,
WorkspaceState.MediaRemoved => StatusKind.NoProxies,
WorkspaceState.Gone => StatusKind.Warning,
WorkspaceState.Damaged => StatusKind.Error,
_ => StatusKind.Queued,
};
/// What the state means and what to do, with the counts behind it, worded for the project's home.
public static string StateToolTip(WorkspaceStatus? status, bool syncing = false, bool server = false) =>
syncing ? ForHome("Tooltips.Editor.Workspace.State.Syncing", server)
: status is null ? ForHome("Tooltips.Editor.Workspace.State.Reading", server)
: status.State switch
{
WorkspaceState.Ahead => ForHome("Tooltips.Editor.Workspace.State.Ahead", server, Formatting.Count(status.Ahead)),
WorkspaceState.Behind => ForHome("Tooltips.Editor.Workspace.State.Behind", server, Formatting.Count(status.Behind)),
WorkspaceState.Offline when status.Ahead > 0 => ForHome("Tooltips.Editor.Workspace.State.OfflineAhead", server, Formatting.Count(status.Ahead)),
var state => ForHome("Tooltips.Editor.Workspace.State." + state, server),
};
/// "Saved", "Merged", "Restored", "Imported", "Outside change".
public static string VersionKind(ProjectVersionKind kind) => Loc.L("Editor.History.Kind." + kind);
///
/// Who made a version: its author, else the PC it was made on ("STUDIO-PC"), however the program that made it named
/// itself ("chronos@STUDIO-PC" for the archive's own versions, "Chronos on STUDIO-PC" for those of test builds).
///
public static string Author(ProjectVersion version)
{
ArgumentNullException.ThrowIfNull(version);
if (version.Author is { Length: > 0 } author) return author;
var client = version.ClientName?.Trim() ?? string.Empty;
foreach (var prefix in ClientPrefixes)
{
if (client.Length > prefix.Length && client.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) return client[prefix.Length..];
}
return client;
}
/// What programs put before the PC's name in a version's client name (not words of the UI: the PC alone is shown).
private static readonly string[] ClientPrefixes = ["chronos@", "server@", "workspace@", "Chronos on "];
/// "28/10/2026 18:02".
public static string When(DateTimeOffset at) => $"{Formatting.Date(at)} {Formatting.TimeOfDay(at)}";
///
/// One line per setting both sides changed ("Deflicker window 41 here, 33 in the library"), at most .
/// A conflict of format () reads as its cause, never as the format's numbers.
///
public static IReadOnlyList ConflictLines(IEnumerable differences, int max, bool server = false)
{
ArgumentNullException.ThrowIfNull(differences);
var list = differences.ToList();
if (list.Any(d => d.Path == ProjectMerge.FormatPath)) return [Loc.L("Editor.Workspace.Conflict.NewerFormat")];
return SyncText.Differences(list, max, (label, mine, theirs) => ForHome("Editor.Workspace.Difference", server, label, mine, theirs));
}
/// One line per setting that differs between now and a version ("Deflicker window 41 now, 33 in that version").
public static IReadOnlyList CompareLines(IEnumerable differences, int max) =>
SyncText.Differences(differences, max, (label, now, then) => Loc.L("Editor.History.Difference", label, now, then));
///
/// Why a workspace operation stopped, as one localized sentence chosen by cause and worded for the project's home; the
/// exception's own text goes to the log.
///
public static string Failure(Exception ex, bool server = false) => ex switch
{
WorkspaceException or LeaseUnavailableException => ex.Message,
// A library that can be read but not written (a read-only share, a write-protected disk): the work waits here as offline.
HomeUnavailableException { InnerException: ArchiveOfflineException { Availability: ArchiveAvailability.ReadOnly } }
or ArchiveOfflineException { Availability: ArchiveAvailability.ReadOnly } => Loc.L("Errors.Workspace.ReadOnlyHome"),
HomeUnavailableException or ArchiveOfflineException => ForHome("Errors.Workspace.Offline", server),
ProjectException { Reason: ProjectError.NameTaken } => Loc.L("Errors.Workspace.NameTaken"),
ProjectException { Reason: ProjectError.InvalidName } => Loc.L("Errors.Workspace.InvalidName"),
ProjectException { Reason: ProjectError.MainCannotBeDeleted } => Loc.L("Errors.Workspace.MainKept"),
ProjectException => ForHome("Errors.Workspace.ProjectGone", server),
// A version over the size one may be: saved here (refused before anything was written) or sent (the home stored nothing).
ProjectVersionTooLargeException or WorkspaceSyncException { Outcome: PushOutcome.TooLarge } =>
ForHome("Errors.Workspace.VersionTooLarge", server, ProjectSidecars.MaxVersionBytes >> 20),
WorkspaceSyncException => ForHome("Errors.Workspace.Refused", server),
// A server's refusal that keeps its meaning: an account that may not change projects there, above all.
ChronosApiException { Status: HttpStatusCode.Forbidden } => Loc.L("Errors.Workspace.Forbidden"),
ChronosApiException api => ErrorText.ForServer(api),
InvalidDataException => Loc.L("Errors.Workspace.Damaged"),
Editor.EditorException => ex.Message,
_ => ArchiveFailures.Cause(ex),
};
}