using System.Globalization;
namespace Chronos.App.Jobs;
///
/// The job log stores each line's time of day in UTC ("12:35:04 Copying…"), the same on the server and the desktop.
/// The Jobs table shows its times in local time, so the log's are shown in local time too (#70).
///
public static class JobLogTimes
{
///
/// with each leading HH:mm:ss turned from UTC into 's time.
/// The log keeps no dates, so they are worked out backwards from (when the job finished, or
/// now): each line is the latest instant at or before the line after it, so a run that goes past midnight UTC, or lasts
/// days, dates its lines right and a daylight-saving change in between converts each side with its own offset. A pause
/// of a day or more between two lines cannot be seen, and those lines keep the later day's date. Lines without a time
/// stay as they are.
///
public static string ToLocal(string tail, DateTimeOffset reference, TimeZoneInfo zone)
{
ArgumentNullException.ThrowIfNull(tail);
ArgumentNullException.ThrowIfNull(zone);
if (tail.Length == 0) return tail;
// A minute of slack: the reference may be read a little before the last line's clock (another machine's).
var next = reference.UtcDateTime.AddMinutes(1);
var lines = tail.Split('\n');
for (var i = lines.Length - 1; i >= 0; i--)
{
var line = lines[i];
if (line.Length < 9 || line[8] != ' ' ||
!TimeSpan.TryParseExact(line.AsSpan(0, 8), @"hh\:mm\:ss", CultureInfo.InvariantCulture, out var time)) continue;
var utc = DateTime.SpecifyKind(next.Date + time, DateTimeKind.Utc);
if (utc > next) utc = utc.AddDays(-1);
next = utc;
var local = TimeZoneInfo.ConvertTimeFromUtc(utc, zone);
lines[i] = local.ToString("HH:mm:ss", CultureInfo.InvariantCulture) + line[8..];
}
return string.Join('\n', lines);
}
}