namespace MauiTestApp.Graphing
{
    public class Graph : IDrawable
    {
        private List<float> Data = new();
        private float Average = 0, AvgPos = 0, Min = 0, Max = 0;

        private const float ScaleY = 200;
        private const float ScaleX = 300;
        private const float OffsetX = 50;

        public void Draw(ICanvas canvas, RectF dirtyRect)
        {
            var cyan = Color.FromArgb("28C2D1");
            canvas.FillColor = cyan;
            canvas.FontColor = cyan;
            canvas.Font = Microsoft.Maui.Graphics.Font.DefaultBold;
            canvas.StrokeColor = Colors.Red;
            canvas.DrawLine(OffsetX, ScaleY - AvgPos, ScaleX + OffsetX, ScaleY - AvgPos);
            canvas.StrokeColor = cyan;
            canvas.StrokeSize = 2;
            canvas.DrawLine(OffsetX, 0, OffsetX, ScaleY);
            canvas.DrawString($"{Max:0.#.##E+0}", 0, 0, HorizontalAlignment.Left);
            canvas.DrawString($"{Min:0.#.##E+0}", 0, ScaleY, HorizontalAlignment.Left);
            canvas.DrawString($"[ms]", 0, ScaleY+20, HorizontalAlignment.Left);
            canvas.FontColor = Colors.Red;
            canvas.DrawString($"{Average:0.#.##E+0}", 0, ScaleY - AvgPos, HorizontalAlignment.Left);

            float step = ScaleX / (Data.Count + 1);
            for (int i = 0; i < Data.Count; i++)
            {
                canvas.FillCircle(step * (i+1) + OffsetX, ScaleY - Data[i], 2);
            }
        }

        public void Update(List<float> newData)
        {
            if (newData.Count == 0) return;
            Max = newData.Max();
            Min = newData.Min();

            float scaler = Max - Min != 0 ? ScaleY / (Max - Min) : 0;

            Average = newData.Average();
            AvgPos = scaler * (Average - Min);


            Data = newData.Select(x => scaler * (x - Min)).ToList();
        }
    }
}
