using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Windows;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using ConeCalorimeter.Services;
using Microsoft.Win32;
using Serilog;

namespace ConeCalorimeter.ViewModels;

public sealed class RealtimeDataViewModel : PageViewModel
{
    private readonly Action _closeAction;
    private readonly IExperimentDataService _experimentDataService;
    private readonly IRealtimeDataExportService _realtimeDataExportService;
    private string _statusText = string.Empty;

    public RealtimeDataViewModel(
        IExperimentDataService experimentDataService,
        IRealtimeDataExportService realtimeDataExportService,
        Action closeAction) : base("实时数据")
    {
        _experimentDataService = experimentDataService;
        _realtimeDataExportService = realtimeDataExportService;
        _closeAction = closeAction;

        Rows = [];
        CloseCommand = new RelayCommand(_closeAction);
        ClearCommand = new RelayCommand(ClearRows);
        ExportCommand = new RelayCommand(ExportRows);

        RebuildRows();
        _experimentDataService.Records.CollectionChanged += RecordsChanged;
        _experimentDataService.HeatReleaseCorrectionStatusChanged += (_, _) => RebuildRows();
    }

    public ObservableCollection<RealtimeDataRowViewModel> Rows { get; }

    public IRelayCommand CloseCommand { get; }

    public IRelayCommand ClearCommand { get; }

    public IRelayCommand ExportCommand { get; }

    public string StatusText
    {
        get => _statusText;
        private set => SetProperty(ref _statusText, value);
    }

    private void RecordsChanged(object? sender, NotifyCollectionChangedEventArgs e)
    {
        if (e.Action == NotifyCollectionChangedAction.Add && e.NewItems is not null)
        {
            foreach (var item in e.NewItems)
            {
                if (item is ConeCalorimeter.Models.RealtimeDataRecord record)
                {
                    Rows.Add(new RealtimeDataRowViewModel(record));
                }
            }

            StatusText = $"记录数：{Rows.Count}";
            return;
        }

        RebuildRows();
    }

    private void RebuildRows()
    {
        Rows.Clear();
        foreach (var record in _experimentDataService.Records)
        {
            Rows.Add(new RealtimeDataRowViewModel(record));
        }

        StatusText = $"记录数：{Rows.Count}";
    }

    private void ClearRows()
    {
        _experimentDataService.ClearRecords();
    }

    private void ExportRows()
    {
        var records = _experimentDataService.Records.ToList();
        if (records.Count == 0)
        {
            StatusText = "没有可导出的数据";
            Log.Warning("Realtime data export blocked because there are no records.");
            return;
        }

        var dialog = new SaveFileDialog
        {
            Title = "导出实时数据",
            Filter = "Excel 97-2003 工作簿 (*.xls)|*.xls",
            FileName = $"实时数据_{DateTime.Now:yyyyMMdd_HHmmss}.xls",
            DefaultExt = ".xls",
            AddExtension = true,
            OverwritePrompt = true
        };

        if (dialog.ShowDialog() != true)
        {
            StatusText = "已取消导出";
            return;
        }

        try
        {
            _realtimeDataExportService.Export(dialog.FileName, records);
            StatusText = $"已导出：{dialog.FileName}";
            Log.Information("Realtime data export succeeded. Path={Path}, Records={RecordCount}.", dialog.FileName, records.Count);
        }
        catch (Exception ex)
        {
            StatusText = $"导出失败：{ex.Message}";
            Log.Error(ex, "Realtime data export failed. Path={Path}, Records={RecordCount}.", dialog.FileName, records.Count);
            MessageBox.Show(StatusText, "导出实时数据", MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

}
