using Harmonia.WinUI.ViewModels;
using Microsoft.UI.Input;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Input;

namespace Harmonia.WinUI.Views;

public sealed partial class PlayerView : UserControl
{
    private readonly PlayerViewModel _viewModel;

    public PlayerView()
    {
        InitializeComponent();
        _viewModel = (PlayerViewModel)DataContext;
    }

    private void PositionSlider_Loaded(object? sender, RoutedEventArgs e)
    {
        if (sender is not Slider slider)
            return;

        PointerEventHandler pointerPressedHandler = new(OnSliderPointerPressed);
        slider.AddHandler(PointerPressedEvent, pointerPressedHandler, true);

        PointerEventHandler pointerReleasedHandler = new(OnSliderPointerReleased);
        slider.AddHandler(PointerReleasedEvent, pointerReleasedHandler, true);
    }

    private void OnSliderPointerPressed(object? sender, PointerRoutedEventArgs e)
    {
        if (sender is not Slider slider)
            return;

        PointerPointProperties pointerProperties = e.GetCurrentPoint(slider).Properties;

        if (pointerProperties.IsLeftButtonPressed == false)
            return;

        _viewModel.IsPositionChangeInProgress = true;
    }

    private void OnSliderPointerReleased(object? sender, PointerRoutedEventArgs e)
    {
        if (sender is not Slider slider)
            return;

        _viewModel.CurrentPosition = slider.Value;
        _viewModel.IsPositionChangeInProgress = false;
    }

    private void VolumeSlider_PointerWheelChanged(object? sender, PointerRoutedEventArgs e)
    {
        if (sender is not Slider slider)
            return;

        var pointerProperties = e.GetCurrentPoint(slider).Properties;
        var mouseWheelDelta = pointerProperties.MouseWheelDelta;

        if (mouseWheelDelta == 0)
            return;

        double delta = mouseWheelDelta > 0 ? .02 : -.02;

        _viewModel.Volume += delta;
    }
}