using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace SHH.CameraDashboard;

public static class TouchBehavior
{
    //原有 Action 属性保持不变...
    public static readonly DependencyProperty ActionProperty =
        DependencyProperty.RegisterAttached("Action", typeof(PtzAction?), typeof(TouchBehavior), new PropertyMetadata(null, OnActionChanged));

    public static PtzAction? GetAction(DependencyObject obj) => (PtzAction?)obj.GetValue(ActionProperty);
    public static void SetAction(DependencyObject obj, PtzAction? value) => obj.SetValue(ActionProperty, value);

    // ★★★ [新增] 私有附加属性，用于记录“是否处于按下状态” ★★★
    private static readonly DependencyProperty IsActiveProperty =
        DependencyProperty.RegisterAttached("IsActive", typeof(bool), typeof(TouchBehavior), new PropertyMetadata(false));

    private static bool GetIsActive(DependencyObject obj) => (bool)obj.GetValue(IsActiveProperty);
    private static void SetIsActive(DependencyObject obj, bool value) => obj.SetValue(IsActiveProperty, value);


    private static void OnActionChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is Button btn)
        {
            btn.PreviewMouseDown -= Btn_PreviewMouseDown;
            btn.PreviewMouseUp -= Btn_PreviewMouseUp;
            btn.MouseLeave -= Btn_PreviewMouseUp;

            if (e.NewValue != null)
            {
                btn.PreviewMouseDown += Btn_PreviewMouseDown;
                btn.PreviewMouseUp += Btn_PreviewMouseUp;
                btn.MouseLeave += Btn_PreviewMouseUp;
            }
        }
    }

    private static void Btn_PreviewMouseDown(object sender, MouseButtonEventArgs e)
    {
        if (sender is Button btn && btn.DataContext is CameraPtzViewModel vm)
        {
            var action = GetAction(btn);
            if (action.HasValue && vm.StartCommand.CanExecute(action.Value))
            {
                // 1. 标记为活跃状态
                SetIsActive(btn, true);

                // 2. 执行开始命令
                vm.StartCommand.Execute(action.Value);

                // (可选) 捕获鼠标，防止快速拖出窗口丢失 MouseUp
                btn.CaptureMouse();
            }
        }
    }

    private static void Btn_PreviewMouseUp(object sender, MouseEventArgs e)
    {
        if (sender is Button btn && btn.DataContext is CameraPtzViewModel vm)
        {
            // ★★★ [核心修改] 只有之前标记为活跃，才执行停止 ★★★
            if (GetIsActive(btn))
            {
                var action = GetAction(btn);
                if (action.HasValue && vm.StopCommand.CanExecute(action.Value))
                {
                    vm.StopCommand.Execute(action.Value);
                }

                // 重置状态
                SetIsActive(btn, false);

                // 释放鼠标
                btn.ReleaseMouseCapture();
            }
        }
    }
}