Catalog/imagecatalog/Services/SettingsService.cs
2026-02-04 19:48:03 +01:00

99 lines
3.5 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using ImageCatalog;
namespace ImageCatalog_2.Services
{
/// <summary>
/// Modern settings service that uses reflection to automatically save/load all properties
/// </summary>
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);
}
else if (prop.PropertyType == typeof(bool))
{
value = _parametriSetup.LeggiParametroBoolean(prop.Name);
}
else if (prop.PropertyType == typeof(int))
{
value = _parametriSetup.LeggiParametro<int>(prop.Name, (int)(prop.GetValue(settings) ?? 0));
}
else if (prop.PropertyType == typeof(double))
{
value = _parametriSetup.LeggiParametro<double>(prop.Name, (double)(prop.GetValue(settings) ?? 0.0));
}
else
{
continue; // Skip unsupported types
}
prop.SetValue(settings, value);
}
catch
{
// Skip properties that can't be loaded
}
}
});
}
private bool IsSerializableType(Type type)
{
return type == typeof(string) ||
type == typeof(int) ||
type == typeof(bool) ||
type == typeof(double) ||
type == typeof(float) ||
type == typeof(decimal);
}
}
}