86 Zeilen
2.8 KiB
C#
86 Zeilen
2.8 KiB
C#
using System.Collections.ObjectModel;
|
|
using System.Linq;
|
|
using System.Windows.Threading;
|
|
using PrinterMonitor.Services;
|
|
|
|
namespace PrinterMonitor.ViewModels;
|
|
|
|
/// <summary>
|
|
/// ViewModel für das Dashboard.
|
|
/// Implementiert IDisposable: DispatcherTimer wird beim Disposen gestoppt,
|
|
/// damit das ViewModel vom GC freigegeben werden kann (kein Timer-Leak).
|
|
/// </summary>
|
|
public class DashboardViewModel : ViewModelBase, IDisposable
|
|
{
|
|
public ObservableCollection<PrinterStatusViewModel> Printers { get; } = new();
|
|
|
|
private readonly PrinterService _printerService;
|
|
private readonly DispatcherTimer _timer;
|
|
private bool _disposed;
|
|
|
|
public DashboardViewModel(PrinterService printerService)
|
|
{
|
|
_printerService = printerService;
|
|
|
|
foreach (var name in _printerService.GetPrinterNames())
|
|
{
|
|
var status = _printerService.GetStatus(name);
|
|
var vm = new PrinterStatusViewModel(name, status?.PrinterType ?? "");
|
|
vm.OnSimulationStateChanged = OnSimulationStateChanged;
|
|
if (status != null)
|
|
vm.Update(status);
|
|
Printers.Add(vm);
|
|
}
|
|
|
|
_timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(500) };
|
|
_timer.Tick += (s, e) => RefreshAll();
|
|
_timer.Start();
|
|
}
|
|
|
|
private void OnSimulationStateChanged(string name, bool lts, bool klappe, bool keineEtiketten)
|
|
=> _printerService.SetSimulationState(name, lts, klappe, keineEtiketten);
|
|
|
|
private void RefreshAll()
|
|
{
|
|
var activeNames = _printerService.GetPrinterNames();
|
|
var activeSet = new HashSet<string>(activeNames, StringComparer.OrdinalIgnoreCase);
|
|
|
|
// Entfernte Drucker aus Collection löschen
|
|
for (int i = Printers.Count - 1; i >= 0; i--)
|
|
{
|
|
if (!activeSet.Contains(Printers[i].Name))
|
|
Printers.RemoveAt(i);
|
|
}
|
|
|
|
// Bestehende aktualisieren
|
|
var existingSet = new HashSet<string>(Printers.Select(p => p.Name), StringComparer.OrdinalIgnoreCase);
|
|
foreach (var vm in Printers)
|
|
{
|
|
var status = _printerService.GetStatus(vm.Name);
|
|
if (status != null)
|
|
vm.Update(status);
|
|
}
|
|
|
|
// Neue Drucker hinzufügen
|
|
foreach (var name in activeNames)
|
|
{
|
|
if (!existingSet.Contains(name))
|
|
{
|
|
var status = _printerService.GetStatus(name);
|
|
var vm = new PrinterStatusViewModel(name, status?.PrinterType ?? "");
|
|
vm.OnSimulationStateChanged = OnSimulationStateChanged;
|
|
if (status != null)
|
|
vm.Update(status);
|
|
Printers.Add(vm);
|
|
}
|
|
}
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
if (_disposed) return;
|
|
_timer.Stop();
|
|
_disposed = true;
|
|
}
|
|
}
|