using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; using ImageCatalog; namespace ImageCatalog_2.Services { /// /// Modern settings service that uses reflection to automatically save/load all properties /// public class SettingsService : ISettingsService { private readonly ParametriSetup _parametriSetup; public SettingsService(ParametriSetup parametriSetup) { _parametriSetup = parametriSetup; } public Task SaveSettingsAsync(string filePath, object settings) { return Task.Run(() => { _parametriSetup.NomeFileSetup = filePath; // Use reflection to get all properties and save them var properties = settings.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(p => p.CanRead && IsSerializableType(p.PropertyType)); foreach (var prop in properties) { var value = prop.GetValue(settings); _parametriSetup.AggiornaParametro(prop.Name, value); } _parametriSetup.SalvaParametriSetup(); }); } public Task LoadSettingsAsync(string filePath, object settings) { return Task.Run(() => { _parametriSetup.NomeFileSetup = filePath; _parametriSetup.CaricaParametriSetup(); // Use reflection to get all properties and load them var properties = settings.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(p => p.CanWrite && IsSerializableType(p.PropertyType)); foreach (var prop in properties) { try { object value; if (prop.PropertyType == typeof(string)) { value = _parametriSetup.LeggiParametroString(prop.Name); // Don't update if empty string and current value is not empty if (string.IsNullOrEmpty((string)value)) { var currentValue = prop.GetValue(settings) as string; if (!string.IsNullOrEmpty(currentValue)) { continue; // Skip if no value in settings but there's a default } } } else if (prop.PropertyType == typeof(bool)) { value = _parametriSetup.LeggiParametroBoolean(prop.Name); } else if (prop.PropertyType == typeof(int)) { value = _parametriSetup.LeggiParametro(prop.Name, (int)(prop.GetValue(settings) ?? 0)); } else if (prop.PropertyType == typeof(double)) { value = _parametriSetup.LeggiParametro(prop.Name, (double)(prop.GetValue(settings) ?? 0.0)); } else { continue; // Skip unsupported types } prop.SetValue(settings, value); } catch (Exception ex) { // Skip properties that can't be loaded System.Diagnostics.Debug.WriteLine($"Failed to load property {prop.Name}: {ex.Message}"); } } }); } private bool IsSerializableType(Type type) { return type == typeof(string) || type == typeof(int) || type == typeof(bool) || type == typeof(double) || type == typeof(float) || type == typeof(decimal); } } }