using System.Text.Json;
using TradingBot.Models;

namespace TradingBot.Services;

public class SettingsService
{
    private const string SettingsFileName = "appsettings.json";
    private AppSettings _settings;
    private readonly string _settingsPath;

    public event Action? OnSettingsChanged;

    public SettingsService()
    {
        _settingsPath = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
            "TradingBot",
            SettingsFileName
        );

        _settings = LoadSettings();
    }

    public AppSettings GetSettings()
    {
        return _settings;
    }

    public void UpdateSettings(AppSettings settings)
    {
        _settings = settings;
        SaveSettings();
        OnSettingsChanged?.Invoke();
    }

    public void UpdateSetting<T>(string propertyName, T value)
    {
        var property = typeof(AppSettings).GetProperty(propertyName);
        if (property != null && property.CanWrite)
        {
            property.SetValue(_settings, value);
            SaveSettings();
            OnSettingsChanged?.Invoke();
        }
    }

    private AppSettings LoadSettings()
    {
        try
        {
            if (File.Exists(_settingsPath))
            {
                var json = File.ReadAllText(_settingsPath);
                var settings = JsonSerializer.Deserialize<AppSettings>(json);
                return settings ?? new AppSettings();
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error loading settings: {ex.Message}");
        }

        return new AppSettings();
    }

    private void SaveSettings()
    {
        try
        {
            var directory = Path.GetDirectoryName(_settingsPath);
            if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }

            var json = JsonSerializer.Serialize(_settings, new JsonSerializerOptions
            {
                WriteIndented = true
            });

            File.WriteAllText(_settingsPath, json);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error saving settings: {ex.Message}");
        }
    }

    public void ResetToDefaults()
    {
        _settings = new AppSettings();
        SaveSettings();
        OnSettingsChanged?.Invoke();
    }
}
