using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(LineRenderer))]
public class ForceCurveHistoryDebugger : MonoBehaviour
{
    private LineRenderer _lr;
    private List<float> _historyPoints = new List<float>();
    
    [Header("Settings")]
    public float xScale = 0.05f;  // Distance between points
    public float yScale = 0.05f;  // Height multiplier
    public int maxPoints = 1000;  // Keep last 1000 points (approx 20-30 seconds)

    private int _lastPointsCount = 0;

    private void Awake()
    {
        _lr = GetComponent<LineRenderer>();
        _lr.positionCount = 0;
        _lr.startWidth = 0.05f;
        _lr.endWidth = 0.05f;
    }

    private void Start()
    {
        if (PerformanceMonitorManager.Instance != null)
        {
            PerformanceMonitorManager.Instance.OnForceCurveUpdated += OnCurveData;
        }
    }

    private void OnCurveData(List<float> fullCurve)
    {
        // Calculate how many NEW points were added since last update
        // (Since the Manager sends the whole cumulative curve of the current stroke)
        int newPointsCount = fullCurve.Count - _lastPointsCount;

        // If count dropped (new stroke started), we take the whole new list
        if (newPointsCount < 0)
        {
            newPointsCount = fullCurve.Count;
            AddPoints(fullCurve); // Add the whole new stroke start
        }
        else if (newPointsCount > 0)
        {
            // Just add the tail (the newest packet)
            List<float> newSegment = fullCurve.GetRange(_lastPointsCount, newPointsCount);
            AddPoints(newSegment);
        }

        _lastPointsCount = fullCurve.Count;
    }

    private void AddPoints(List<float> newPoints)
    {
        UnityMainThreadDispatcher.Instance().Enqueue(() => {
            
            _historyPoints.AddRange(newPoints);

            // Trim history if too long
            if (_historyPoints.Count > maxPoints)
            {
                _historyPoints.RemoveRange(0, _historyPoints.Count - maxPoints);
            }

            DrawGraph();
        });
    }

    private void DrawGraph()
    {
        _lr.positionCount = _historyPoints.Count;
        
        for (int i = 0; i < _historyPoints.Count; i++)
        {
            float x = i * xScale;
            float y = _historyPoints[i] * yScale;
            
            // Shift x so the graph scrolls to the left
            // (Optional: Keep it static and let it grow to the right)
            
            _lr.SetPosition(i, new Vector3(x, y, 0));
        }
    }
}