NetDocsForLLM/ViewModels/LogViewModel.cs

130 lines
3.8 KiB
C#

//--- LogViewModel.cs ---
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using NetDocsForLLM.Services;
using NetDocsForLLM.ViewModels;
using Ookii.Dialogs.Wpf;
using System;
using System.Drawing.Printing;
using System.IO;
using System.Reflection.Metadata;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Media.Media3D;
using System.Windows;
using System.Windows.Threading;
using static System.Net.Mime.MediaTypeNames;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TrayNotify;
namespace NetDocsForLLM.ViewModels
{
public class LogViewModel : ObservableObject
{
private string _logContent;
private int _logLevel;
private readonly DispatcherTimer _refreshTimer;
public string LogContent
{
get => _logContent;
set => SetProperty(ref _logContent, value);
}
public int LogLevel
{
get => _logLevel;
set
{
if (SetProperty(ref _logLevel, value))
{
UpdateLogContent();
}
}
}
public int ErrorCount => AppLogger.ErrorCount;
public int WarningCount => AppLogger.WarningCount;
public int TypeCount => AppLogger.TypeCount;
public int MemberCount => AppLogger.MemberCount;
public IRelayCommand ClearLogCommand { get; }
public IRelayCommand SaveLogCommand { get; }
public IRelayCommand RefreshLogCommand { get; }
public LogViewModel()
{
_logLevel = LogLevel; // Por defecto, mostrar INFO y errores
_logContent = "";
ClearLogCommand = new RelayCommand(ClearLog);
SaveLogCommand = new RelayCommand(SaveLog);
RefreshLogCommand = new RelayCommand(UpdateLogContent);
// Crear timer para actualizar el contenido
_refreshTimer = new DispatcherTimer
{
Interval = TimeSpan.FromSeconds(1)
};
_refreshTimer.Tick += (s, e) => UpdateProperties();
_refreshTimer.Start();
// Suscribirse al evento de actualización de logs
AppLogger.LogUpdated += OnLogUpdated;
UpdateLogContent();
}
private void OnLogUpdated(object sender, EventArgs e)
{
// Este método podría ser llamado desde otro hilo, así que usamos el Dispatcher
App.Current.Dispatcher.InvokeAsync(() =>
{
UpdateLogContent();
UpdateProperties();
});
}
private void UpdateProperties()
{
OnPropertyChanged(nameof(ErrorCount));
OnPropertyChanged(nameof(WarningCount));
OnPropertyChanged(nameof(TypeCount));
OnPropertyChanged(nameof(MemberCount));
}
private void UpdateLogContent()
{
LogContent = AppLogger.GetContent((LogLevel)_logLevel);
}
private void ClearLog()
{
AppLogger.Clear();
UpdateLogContent();
}
private void SaveLog()
{
var dialog = new VistaSaveFileDialog
{
Filter = "Archivos de texto (*.txt)|*.txt|Archivos de log (*.log)|*.log",
DefaultExt = ".txt",
Title = "Guardar archivo de log"
};
if (dialog.ShowDialog() == true)
{
try
{
File.WriteAllText(dialog.FileName, AppLogger.GetContent());
AppLogger.LogInfo($"Log guardado en: {dialog.FileName}");
}
catch (Exception ex)
{
AppLogger.LogError($"Error al guardar el log: {ex.Message}");
}
}
}
}
}