using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
using Chronos.App.Infrastructure;
using Chronos.App.Server;
using Chronos.App.Settings;
using Chronos.App.Shell;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Ui.Controls;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Sections;
/// An address of the shared library with its Copy button.
public sealed record ShareAddressRow(string Address, ICommand CopyCommand);
///
/// Server › This library (owner review 5, #67): whether this PC shares its library, why not when it could not start
/// (with Restart), the addresses with Copy, the ports, the certificate's fingerprint with Copy, the first administrator's
/// temporary password while it exists (Show, Copy), the clients of the last minutes and the admin panel. Off, one row and
/// Sharing settings. Follows on the UI thread; the clients are read again every few seconds.
///
public sealed class SharePanelViewModel : LocalizedViewModel
{
private static readonly TimeSpan RefreshInterval = TimeSpan.FromSeconds(10);
private readonly ShellViewModel _shell;
private readonly LibraryShare _share;
private readonly DispatcherTimer? _timer;
private bool _showPassword;
public SharePanelViewModel(ShellViewModel shell)
{
_shell = shell;
_share = shell.Services.Share;
_share.PropertyChanged += OnShareChanged;
CopyCommand = new RelayCommand(p => Copy(p as string));
CopyFingerprintCommand = new RelayCommand(() => Copy(_share.Fingerprint), () => _share.Fingerprint is not null);
ShowPasswordCommand = new RelayCommand(() =>
{
_showPassword = !_showPassword;
OnPropertyChanged(nameof(PasswordText));
OnPropertyChanged(nameof(ShowPasswordText));
}, () => _share.AdminPassword is not null);
CopyPasswordCommand = new RelayCommand(() => Copy(_share.AdminPassword), () => _share.AdminPassword is not null);
AdminPanelCommand = new RelayCommand(() => ShellActions.OpenUrl($"https://localhost:{_share.HttpsPort}/admin"), () => _share.IsOn && _share.HttpsPort > 0);
RestartCommand = new RelayCommand(() => _ = RestartAsync(), () => _share.State is ShareState.Failed);
SettingsCommand = new RelayCommand(() =>
{
_shell.Settings.Page = SettingsPage.Server;
_shell.Navigate(SectionKey.Settings);
});
if (Application.Current is not null && !shell.Services.Environment.IsCapture)
{
_timer = new DispatcherTimer(DispatcherPriority.Background) { Interval = RefreshInterval };
_timer.Tick += (_, _) =>
{
if (_share.IsOn) _ = RefreshAsync();
};
_timer.Start();
}
}
public ICommand CopyCommand { get; }
public ICommand CopyFingerprintCommand { get; }
public ICommand ShowPasswordCommand { get; }
public ICommand CopyPasswordCommand { get; }
public ICommand AdminPanelCommand { get; }
public ICommand RestartCommand { get; }
public ICommand SettingsCommand { get; }
/// Sharing is on in the settings, whether it runs or not: the details show.
public bool IsShared => _share.State is not ShareState.Off;
public bool IsNotShared => !IsShared;
public bool IsOn => _share.IsOn;
public bool HasFailed => _share.State is ShareState.Failed;
public StatusKind StatusKind => _share.State switch
{
ShareState.On => StatusKind.Online,
ShareState.Starting => StatusKind.Running,
ShareState.Failed => StatusKind.Error,
_ => StatusKind.Offline,
};
public string StateText => Loc.L("Server.Share.State." + _share.State);
public string? Reason => _share.Reason;
public IReadOnlyList Addresses => [.. _share.Addresses.Select(a => new ShareAddressRow(a, CopyCommand))];
public string? PortsText => _share.IsOn ? Loc.L("Server.Share.PortsValue", _share.HttpsPort, _share.HttpPort) : null;
public string? Fingerprint => _share.Fingerprint is { } fingerprint ? Formatting.LeftToRight(fingerprint) : null;
public bool HasAdminPassword => _share.AdminPassword is not null;
/// The temporary password, masked until Show.
public string? PasswordText => _share.AdminPassword is not { } password ? null : _showPassword ? password : new string('•', 12);
public string ShowPasswordText => Loc.L(_showPassword ? "Server.Share.Hide" : "Server.Share.Show");
/// "anna · Chronos Uploader · 192.168.1.20", the latest first.
public IReadOnlyList Clients => [.. _share.Clients.Select(c => Loc.L("Server.Share.ClientRow", c.User, c.Program, c.Address).TrimEnd(' ', '·'))];
public bool HasClients => _share.Clients.Count > 0;
public string ClientsText => HasClients ? Loc.Plural("Server.Share.ClientCount", _share.Clients.Count) : Loc.L("Server.Share.NoClients");
public override void Dispose()
{
_timer?.Stop();
_share.PropertyChanged -= OnShareChanged;
base.Dispose();
}
private async Task RestartAsync()
{
await _share.RestartAsync();
CommandManager.InvalidateRequerySuggested();
}
private async Task RefreshAsync()
{
try
{
await _share.RefreshAsync();
}
catch (Exception ex) when (ex is InvalidOperationException or ObjectDisposedException)
{
Log.Warning("share", "The clients of the shared library could not be read", ex);
}
}
private static void Copy(string? text)
{
if (string.IsNullOrEmpty(text)) return;
try
{
Clipboard.SetText(text);
}
catch (ExternalException ex)
{
// Another program holds the clipboard: nothing was copied, as the next try may.
Log.Warning("share", "The clipboard is busy", ex);
}
}
private void OnShareChanged(object? sender, PropertyChangedEventArgs e)
{
if (Application.Current?.Dispatcher is { } dispatcher && !dispatcher.CheckAccess())
{
dispatcher.BeginInvoke(Changed);
return;
}
Changed();
}
private void Changed()
{
if (!_share.IsOn) _showPassword = false;
OnAllPropertiesChanged();
CommandManager.InvalidateRequerySuggested();
}
}