using System.Windows.Controls;
using LiveChartsCore;
using LiveChartsCore.Kernel;
using LiveChartsCore.Kernel.Sketches;

namespace SharepointToolbox.Views.Tabs;

public partial class StorageView : UserControl
{
    public StorageView(ViewModels.Tabs.StorageViewModel viewModel)
    {
        InitializeComponent();
        DataContext = viewModel;

        StoragePieChart.Tooltip = new SingleSliceTooltip();
    }
}

/// <summary>
/// Custom tooltip that only shows the single closest/hovered pie slice
/// instead of LiveCharts2's default which shows multiple nearby slices.
/// </summary>
internal sealed class SingleSliceTooltip : IChartTooltip
{
    private readonly System.Windows.Controls.ToolTip _tip;

    public SingleSliceTooltip()
    {
        _tip = new System.Windows.Controls.ToolTip
        {
            Padding = new System.Windows.Thickness(8, 4, 8, 4),
            FontSize = 13,
            BorderThickness = new System.Windows.Thickness(1),
        };
        _tip.SetResourceReference(System.Windows.Controls.Control.BackgroundProperty, "SurfaceBrush");
        _tip.SetResourceReference(System.Windows.Controls.Control.ForegroundProperty, "TextBrush");
        _tip.SetResourceReference(System.Windows.Controls.Control.BorderBrushProperty, "BorderSoftBrush");
    }

    public void Show(IEnumerable<ChartPoint> foundPoints, Chart chart)
    {
        // Only show the first (closest) point
        var point = foundPoints.FirstOrDefault();
        if (point == null) { Hide(chart); return; }

        var label = point.Context.Series.GetPrimaryToolTipText(point);
        if (string.IsNullOrEmpty(label)) label = point.Context.Series.Name ?? "";

        _tip.Content = label;
        _tip.IsOpen = true;
    }

    public void Hide(Chart chart)
    {
        _tip.IsOpen = false;
    }
}
