using CommunityToolkit.Mvvm.Input;
using FootwearTest.Services;
using Microsoft.Extensions.Logging;

namespace FootwearTest.ViewModels;

public partial class SettingsViewModel : ViewModelBase
{
    private readonly DeviceSettings _settings;
    private readonly ILogger<SettingsViewModel> _logger;

    public SettingsViewModel(DeviceSettings settings, ILogger<SettingsViewModel> logger)
    {
        _settings = settings;
        _logger = logger;
        Host = settings.Host;
        Port = settings.Port;
        UseSimulator = settings.UseSimulator;
        FootAreaSquareMeters = settings.FootAreaSquareMeters;
        CoefficientOfVariationLimitPercent = settings.CoefficientOfVariationLimitPercent;
        PumpSpeedCubicCentimetersPerHour = settings.PumpSpeedCubicCentimetersPerHour;
        SaveCommand = new RelayCommand(Save);
    }

    public IRelayCommand SaveCommand { get; }

    private string _host = "";
    private int _port;
    private bool _useSimulator;
    private double _footAreaSquareMeters;
    private double _coefficientOfVariationLimitPercent;
    private double _pumpSpeedCubicCentimetersPerHour;
    private string _saveStatus = "参数未保存";

    public string Host { get => _host; set => SetProperty(ref _host, value); }
    public int Port { get => _port; set => SetProperty(ref _port, value); }
    public bool UseSimulator { get => _useSimulator; set => SetProperty(ref _useSimulator, value); }
    public double FootAreaSquareMeters { get => _footAreaSquareMeters; set => SetProperty(ref _footAreaSquareMeters, value); }
    public double CoefficientOfVariationLimitPercent { get => _coefficientOfVariationLimitPercent; set => SetProperty(ref _coefficientOfVariationLimitPercent, value); }
    public double PumpSpeedCubicCentimetersPerHour { get => _pumpSpeedCubicCentimetersPerHour; set => SetProperty(ref _pumpSpeedCubicCentimetersPerHour, value); }
    public string SaveStatus { get => _saveStatus; set => SetProperty(ref _saveStatus, value); }

    private void Save()
    {
        _settings.Host = Host;
        _settings.Port = Port;
        _settings.UseSimulator = UseSimulator;
        _settings.FootAreaSquareMeters = FootAreaSquareMeters;
        _settings.CoefficientOfVariationLimitPercent = CoefficientOfVariationLimitPercent;
        _settings.PumpSpeedCubicCentimetersPerHour = PumpSpeedCubicCentimetersPerHour;
        SaveStatus = "参数已保存，新的试验流程将使用当前设置";
        _logger.LogInformation(
            "Settings saved. UseSimulator={UseSimulator}, Host={Host}, Port={Port}, FootAreaSquareMeters={FootArea}, PumpSpeed={PumpSpeed}",
            UseSimulator,
            Host,
            Port,
            FootAreaSquareMeters,
            PumpSpeedCubicCentimetersPerHour);
    }
}
