import 'package:flutter/material.dart';

import 'point.dart';

class ChartPainter extends CustomPainter {
  final List<Point<double>> data;
  final double maxY;
  final BuildContext context;

  ChartPainter({
    required this.data,
    required this.maxY,
    required this.context,
  });

  @override
  void paint(Canvas canvas, Size size) async {
    final paint = Paint()
      ..style = PaintingStyle.stroke
      ..strokeWidth = 1.5
      ..color = Theme.of(context).colorScheme.primary;

    // A path object to store the graph's lines
    Path path = Path();

    if (data.isNotEmpty) {
      // Calculate the maximum and minimum y values in the data
      const minY = 0;

      // Calculate the scaling factor for the y values
      double yScale = 1;
      final yTranslation = size.height;
      yScale = yTranslation / maxY.abs();

      if (minY.abs() > yTranslation) {
        final scale = yTranslation / minY.abs();
        if (maxY.abs() < minY.abs()) {
          yScale = scale;
        }
      }

      // Start the path at the first data point
      path.moveTo(
        data.first.x + size.width,
        yTranslation - (data.first.y * yScale),
      );

      // Plot the lines between each subsequent data point
      for (int i = 0; i < data.length - 1; i++) {
        final y = data[i + 1].y * yScale;
        final x = data[i + 1].x + size.width;
        path.lineTo(x, yTranslation - y);
      }
    }

    // Draw the path on the canvas
    canvas.drawPath(path, paint);
  }

  paintRect(Canvas canvas, Size size, double posX, double posY) {
    final Rect rect = Offset(posX, posY) & const Size(10, 10);
    canvas.drawRect(rect, Paint()..color = Colors.red);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}
