import 'package:flutter/foundation.dart';
import 'package:flyinsono/lab/pages/lab_image/widgets/vid_repaint_overlay/controller.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'dart:ui' as ui;

class VidRepaintLayer extends GetView<VidRepaintOverlayController> {
  const VidRepaintLayer({
    Key? key,
    required this.tabHashCode,
  }) : super(key: key);

  @override
  String? get tag => tabHashCode;

  final String tabHashCode;

  @override
  Widget build(BuildContext context) {
    return GetBuilder<VidRepaintOverlayController>(
      tag: tabHashCode,
      id: VidRepaintOverlayController.vidRepaintCanavsId,
      builder: (_) {
        if (!controller.isURMParamLoaded) {
          return Container();
        }
        if (controller.isSyncDisplay) {
          return ClipRect(
            child: SizedBox.expand(
              child: RepaintBoundary(
                child: CustomPaint(
                  painter: _ZoomedVidDisplayPainter(
                    vidImage: controller.vidImage,
                  ),
                ),
              ),
            ),
          );
        } else {
          return Container();
        }
      },
    );
  }
}

class _ZoomedVidDisplayPainter extends CustomPainter {
  _ZoomedVidDisplayPainter({
    required this.vidImage,
  });

  final ui.Image? vidImage;

  @override
  void paint(Canvas canvas, Size size) {
    if (vidImage == null) return;
    Rect dst = Rect.fromLTWH(0, 0, size.width, size.height);

    final paint = Paint();
    final src = Rect.fromLTWH(
        0, 0, vidImage!.width.toDouble(), vidImage!.height.toDouble());
    canvas.drawImageRect(vidImage!, src, dst, paint);

    if (!kDebugMode) {
      return;
    }
    // 黄色画笔，把画布框起来
    paint
      ..color = Colors.yellow
      ..style = PaintingStyle.stroke
      ..strokeWidth = 1;
    // 给 dst 加 1 的padding
    // dst = dst.deflate(2);
    canvas.drawRect(dst, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}
