using System.Windows;
using ConeCalorimeter.Services;
using ConeCalorimeter.ViewModels;
using Serilog;

namespace ConeCalorimeter
{
    public partial class MainWindow : Window
    {
        private readonly ITcpDeviceConnectionService _tcpDeviceConnectionService;
        private readonly IScaleService _scaleService;

        public MainWindow()
        {
            InitializeComponent();

            var tcpOptions = TcpDeviceConnectionOptions.FromEnvironment();
            var scaleOptions = SerialScaleOptions.FromEnvironment();

            _tcpDeviceConnectionService = new TcpDeviceConnectionService(tcpOptions);
            _scaleService = new ModbusRtuScaleService(scaleOptions);
            Log.Information(
                "Main window initialized. TCP endpoint={Endpoint}, scale port={ScalePort}.",
                _tcpDeviceConnectionService.Endpoint,
                scaleOptions.PortName);
            _ = _tcpDeviceConnectionService.StartAsync();

            var experimentDataService = new ExperimentDataService(
                new ModbusRealtimeDataService(_tcpDeviceConnectionService, _scaleService));
            DataContext = new MainViewModel(
                experimentDataService,
                _tcpDeviceConnectionService,
                new NpoiReportExportService(),
                new NpoiRealtimeDataExportService(),
                new HelpDialogService());
        }

        protected override async void OnClosed(EventArgs e)
        {
            Log.Information("Main window closing; disposing device services.");
            _scaleService.Dispose();
            await _tcpDeviceConnectionService.DisposeAsync();
            base.OnClosed(e);
        }
    }
}
