using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
using Titano.Core.Diagnostics;
using Titano.Core.IO;
using Titano.Ui.Theming;
using Titano.Uploader.Uploads;
namespace Titano.Uploader.Infrastructure;
///
/// uploader.json. The bearer token is stored only DPAPI-protected for the current Windows user
/// (); "Start with Windows" lives in the registry, which stays the source of truth.
///
public sealed class UploaderSettings
{
public string? ServerUrl { get; set; }
public string? Username { get; set; }
/// Base64 of the DPAPI (CurrentUser) blob of the bearer token.
public string? ProtectedToken { get; set; }
/// SHA-256 fingerprints (XX:XX:…) of self-signed certificates the user trusted (TOFU).
public List TrustedFingerprints { get; set; } = [];
/// Upload limit in MB/s (decimal megabytes); 0 = unlimited.
public int BandwidthLimit { get; set; }
public bool MinimizeToTray { get; set; } = true;
public bool DeleteAfterUpload { get; set; }
public UploadTargetMode Target { get; set; } = UploadTargetMode.Sessions;
public Guid? TargetSequenceId { get; set; }
public string? NewSequenceTitle { get; set; }
public List WatchFolders { get; set; } = [];
public string? Language { get; set; }
public AppTheme Theme { get; set; } = AppTheme.Dark;
public WindowPlacement? Window { get; set; }
public sealed class WatchFolderSettings
{
public string Path { get; set; } = string.Empty;
public int IntervalSeconds { get; set; } = 60;
}
public sealed class WindowPlacement
{
public double Left { get; set; }
public double Top { get; set; }
public double Width { get; set; }
public double Height { get; set; }
}
public static UploaderSettings Load(string path)
{
try
{
if (File.Exists(path))
return JsonSerializer.Deserialize(File.ReadAllBytes(path), UploaderSettingsJson.Default.UploaderSettings) ?? new UploaderSettings();
}
catch (JsonException ex)
{
// A corrupt settings file must never block startup; defaults apply.
Log.Warning("settings", "uploader.json unreadable; using defaults", ex);
}
catch (IOException ex)
{
Log.Warning("settings", "uploader.json unreadable; using defaults", ex);
}
return new UploaderSettings();
}
public void Save(string path) => AtomicFile.WriteAllBytes(path, JsonSerializer.SerializeToUtf8Bytes(this, UploaderSettingsJson.Default.UploaderSettings));
}
[JsonSourceGenerationOptions(WriteIndented = true, PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, UseStringEnumConverter = true)]
[JsonSerializable(typeof(UploaderSettings))]
internal sealed partial class UploaderSettingsJson : JsonSerializerContext;