EscribePassword/MainWindow.xaml.cs

178 lines
5.2 KiB
C#
Raw Normal View History

2024-06-15 06:24:07 -03:00
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text.Json;
using System.IO;
using System.Windows;
2024-06-15 14:33:52 -03:00
using WindowsInput;
using WindowsInput.Native;
using Application = System.Windows.Application;
using System.Windows.Input;
using MouseButton = System.Windows.Input.MouseButton;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using ListBox = System.Windows.Controls.ListBox;
2024-06-15 06:24:07 -03:00
namespace EscribePassword
{
2024-06-15 14:33:52 -03:00
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Loaded += MainWindow_Loaded;
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
((App)Application.Current).SetInitialWindowPosition();
}
private void Window_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton == MouseButton.Left)
{
this.DragMove();
}
}
}
2024-06-15 06:24:07 -03:00
public partial class MView : ObservableObject
{
[ObservableProperty]
private ObservableCollection<Passwords> passwords;
[ObservableProperty]
private Passwords selectedPassword;
public MView()
{
// Suscribirse al evento de cierre de la aplicación
Application.Current.Exit += OnApplicationExit;
passwords = new ObservableCollection<Passwords>(EstadoPersistente.Instance.Passwords);
}
private void OnApplicationExit(object sender, ExitEventArgs e)
{
EstadoPersistente.Instance.Passwords = new List<Passwords>(passwords);
EstadoPersistente.Instance.GuardarEstado();
}
2024-06-15 14:33:52 -03:00
[RelayCommand]
2024-06-15 06:24:07 -03:00
private void Agregar()
{
Passwords newPassword = new Passwords { Usuario = "NuevoUsuario", Password = "NuevaContraseña" };
passwords.Add(newPassword);
SelectedPassword = newPassword;
}
2024-06-15 14:33:52 -03:00
[RelayCommand]
2024-06-15 06:24:07 -03:00
private void Eliminar(Passwords password)
{
if (password != null)
{
passwords.Remove(password);
SelectedPassword = null;
}
}
2024-06-15 14:33:52 -03:00
[RelayCommand]
private void Utilizar(Passwords password)
{
if (password != null)
{
((App)Application.Current).PasteLogic.RestoreAndSimulatePaste(password);
// Cerrar la aplicación después de la acción
Application.Current.Shutdown();
}
}
[RelayCommand]
private void Cerrar()
{
// Cerrar la aplicación después de la acción
Application.Current.Shutdown();
}
2024-06-15 06:24:07 -03:00
}
2024-06-15 14:33:52 -03:00
internal class EstadoPersistente
2024-06-15 06:24:07 -03:00
{
// Ruta donde se guardará el estado
private static readonly string _filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "estado.json");
// Instancia privada estática, parte del patrón Singleton
private static EstadoPersistente _instance;
private List<Passwords> passwords;
public List<Passwords> Passwords
{
get
{
if (passwords == null) passwords = new List<Passwords>();
return passwords;
}
set
{
passwords = value;
}
}
// Constructor público sin parámetros requerido para la deserialización
public EstadoPersistente()
{
passwords = new List<Passwords>();
}
// Propiedad pública estática para acceder a la instancia
public static EstadoPersistente Instance
{
get
{
if (_instance == null)
{
_instance = CargarEstado();
}
return _instance;
}
}
// Método para guardar el estado en un archivo JSON
public void GuardarEstado()
{
var options = new JsonSerializerOptions
{
WriteIndented = true // para una salida JSON formateada legiblemente
};
string json = JsonSerializer.Serialize(this, options);
File.WriteAllText(_filePath, json);
}
// Método estático para cargar el estado desde un archivo JSON
private static EstadoPersistente CargarEstado()
{
try
{
if (File.Exists(_filePath))
{
string json = File.ReadAllText(_filePath);
return JsonSerializer.Deserialize<EstadoPersistente>(json);
}
return new EstadoPersistente(); // Devuelve una nueva instancia si no existe el archivo
}
catch
{
return new EstadoPersistente(); // Devuelve una nueva instancia si hay un error durante la carga
}
}
}
}