import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:myhr_facescan/models/face_position.dart';

class RectanglePainter extends CustomPainter {
  final List<FacePosition> positions;

  final double paperWidth;
  final double paperHeight;

  final List<String> topMessage;
  Color rectColor;
  double rectStrokeWidth;

  RectanglePainter(
      {super.repaint,
      required this.positions,
      required this.paperWidth,
      required this.paperHeight,
      required this.topMessage,
      this.rectColor = const Color.fromRGBO(21, 101, 192, 1),
      this.rectStrokeWidth = 1});

  @override
  void paint(Canvas canvas, Size size) {
    var paint1 = Paint()
      ..color = rectColor
      ..style = PaintingStyle.stroke
      ..strokeWidth = rectStrokeWidth;

    const textStyle = TextStyle(
      color: Colors.green,
      // fontSize: 30,
    );

    for (var pos in positions) {
      final xc = lerpDouble(0, size.width, pos.x / paperWidth)!;
      final yc = lerpDouble(0, size.height, pos.y / paperHeight)!;
      final width = lerpDouble(0, size.width, pos.width / paperWidth)!;

      canvas.drawRect(
          Rect.fromCenter(center: Offset(xc, yc), width: width, height: width),
          paint1);

      var textSpan = TextSpan(
        text: topMessage[positions.indexOf(pos)],
        style: textStyle,
      );
      final textPainter = TextPainter(
        text: textSpan,
        textDirection: TextDirection.ltr,
      );
      textPainter.layout(
        minWidth: 0,
        maxWidth: size.width,
      );
      final xCenter = xc - (width / 2);
      final yCenter = yc - (width / 2) - 20;
      textPainter.paint(canvas, Offset(xCenter, yCenter));
    }
  }

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

  @override
  bool? hitTest(Offset position) {
    // TODO: implement hitTest
    return super.hitTest(position);
  }
}
