using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using LindtLeerformPlugin.Services;
namespace LindtLeerformPlugin.ViewModels;
public partial class CellHistogramViewModel : ObservableObject
{
[ObservableProperty] private string _title = "Cell Histogram";
public int CellIndex { get; set; }
public int[] Bins { get; init; } = [5, 5, 5];
[ObservableProperty] private float[]? _cellHistogram;
[ObservableProperty] private float[]? _cellSpline;
[ObservableProperty] private float[] _averageSpline = new float[SplineCurve.KnotCount];
[ObservableProperty] private string _verdictText = string.Empty;
public bool HasOverride => CellSpline is { Length: SplineCurve.KnotCount };
///
/// Invoked by the view when the user releases the mouse after dragging a spline handle.
/// Lets the calibration window re-test and refresh its preview while the dialog stays open.
///
public Action? DragCompleted { get; set; }
public void RaiseDragCompleted() => DragCompleted?.Invoke(AverageSpline, CellSpline);
partial void OnCellSplineChanged(float[]? value)
{
OnPropertyChanged(nameof(HasOverride));
UpdateVerdict();
}
partial void OnAverageSplineChanged(float[] value) => UpdateVerdict();
partial void OnCellHistogramChanged(float[]? value) => UpdateVerdict();
[RelayCommand]
private void CreateOverride()
{
// Seed from THIS cell's histogram so the user gets a useful starting envelope.
CellSpline = SplineCurve.CreateDefault(CellHistogram);
}
[RelayCommand]
private void RemoveOverride()
{
CellSpline = null;
}
private void UpdateVerdict()
{
var hist = CellHistogram;
if (hist == null || hist.Length == 0)
{
VerdictText = string.Empty;
return;
}
var spline = CellSpline is { Length: SplineCurve.KnotCount } ? CellSpline : AverageSpline;
if (spline is not { Length: SplineCurve.KnotCount })
{
VerdictText = string.Empty;
return;
}
var (isGood, exceed) = LindtLeerformPlugin.Services.LeerformPatternRecognitionService
.EvaluateAgainstSpline(hist, spline);
var label = isGood ? "GOOD" : "BAD";
var splineLabel = HasOverride ? "cell spline" : "average spline";
VerdictText = $"Verdict: {label} Max exceedance: {exceed:F4} Using: {splineLabel}";
}
}