using System.Windows;
using System.Windows.Controls;
using Serilog;
using XplorePlane.ViewModels;

namespace XplorePlane.Views
{
    public partial class PipelineEditorView : UserControl
    {
        public PipelineEditorView()
        {
            InitializeComponent();
            Loaded += OnLoaded;
        }

        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            Log.Information("PipelineEditorView DataContext 类型={Type}",
                DataContext?.GetType().Name);

            PipelineListBox.AllowDrop = true;
            PipelineListBox.Drop += OnOperatorDropped;
            PipelineListBox.DragOver += OnDragOver;
            Log.Debug("PipelineEditorView 原生 Drop 目标已注册");
        }

        private void OnDragOver(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(OperatorToolboxView.DragFormat))
                e.Effects = DragDropEffects.Copy;
            else
                e.Effects = DragDropEffects.None;
            e.Handled = true;
        }

        private void OnOperatorDropped(object sender, DragEventArgs e)
        {
            if (DataContext is not PipelineEditorViewModel vm)
            {
                Log.Warning("Drop 事件触发但 DataContext 不是 PipelineEditorViewModel");
                return;
            }

            if (!e.Data.GetDataPresent(OperatorToolboxView.DragFormat))
            {
                Log.Warning("Drop 事件触发但数据中无 {Format}", OperatorToolboxView.DragFormat);
                return;
            }

            var operatorKey = e.Data.GetData(OperatorToolboxView.DragFormat) as string;
            if (string.IsNullOrEmpty(operatorKey))
            {
                Log.Warning("Drop 事件触发但 OperatorKey 为空");
                return;
            }

            Log.Information("算子已放入流水线：{OperatorKey}，VM HashCode={Hash}，当前节点数（执行前）={Count}",
                operatorKey, vm.GetHashCode(), vm.PipelineNodes.Count);
            vm.AddOperatorCommand.Execute(operatorKey);
            Log.Information("AddOperator 执行后节点数={Count}，PipelineListBox.Items.Count={ItemsCount}",
                vm.PipelineNodes.Count, PipelineListBox.Items.Count);
            e.Handled = true;
        }
    }
}
