using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Harmonia.UI.ViewModels;

namespace Harmonia.UI.Views;

public partial class PlaybackBar : UserControl
{
    private readonly PlaybackBarViewModel _viewModel;

    public PlaybackBar()
    {
        InitializeComponent();
        _viewModel = (PlaybackBarViewModel)DataContext!;
    }

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

        slider.AddHandler(PointerPressedEvent, OnSliderPointerPressed, RoutingStrategies.Tunnel);
        slider.AddHandler(PointerReleasedEvent, OnSliderPointerReleased, RoutingStrategies.Tunnel);
    }

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

        PointerPoint currentPoint = e.GetCurrentPoint(slider);

        if (currentPoint.Properties.IsLeftButtonPressed == false)
            return;

        _viewModel.IsPositionChangeInProgress = true;
    }

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

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

    private void VolumeSlider_PointerWheelChanged(object? sender, PointerWheelEventArgs e)
    {
        double mouseWheelDelta = e.Delta.Y;

        if (mouseWheelDelta == 0)
            return;

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

        _viewModel.Volume += delta;
    }
}