// ignore_for_file: must_be_immutable

import 'package:flutter/material.dart';
import 'package:flyinsono/lab/pages/lab_image/widgets/image_measure_overlay/controller.dart';
import 'package:fis_measure/interfaces/process/annotations/annotation.dart';
import 'package:get/get.dart';

class AnnotationRecordCanvasLayer
    extends GetView<ImageMeasureOverlayController> {
  AnnotationRecordCanvasLayer({
    Key? key,
    required this.tabHashCode,
    this.isURMImage = false,
  }) : super(key: key);

  @override
  String? get tag => tabHashCode;

  final String tabHashCode;

  final bool isURMImage;

  @override
  Widget build(BuildContext context) {
    return GetBuilder<ImageMeasureOverlayController>(
      tag: tabHashCode,
      id: ImageMeasureOverlayController.annotationRecordCanvasLayerId,
      builder: (_) {
        if (controller.app == null) return const SizedBox();

        final List<IAnnotationItemFeature> annotationFeatures = controller
            .app!.annotationItems
            .expand((item) => item.features)
            .toList();
        final hasNoData = annotationFeatures.isEmpty;

        return LayoutBuilder(
          builder: (context, constraints) {
            controller.updateImageWidth(constraints.maxWidth);
            if (hasNoData) {
              return const SizedBox();
            }

            return ClipRect(
              child: SizedBox(
                width: constraints.maxWidth,
                height: constraints.maxHeight,
                child: RepaintBoundary(
                  child: CustomPaint(
                    painter: _PanelPainter(
                      annotationFeatures,
                      isURMImage,
                    ),
                  ),
                ),
              ),
            );
          },
        );
      },
    );
  }
}

class _PanelPainter extends CustomPainter {
  final List<IAnnotationItemFeature> annotationFeatures;

  /// 是否是URM 图
  final bool isURMImage;
  _PanelPainter(
    this.annotationFeatures,
    this.isURMImage,
  );

  @override
  void paint(Canvas canvas, Size size) {
    for (final feature in annotationFeatures) {
      feature.paint(canvas, size);
    }
  }

  @override
  bool shouldRepaint(covariant _PanelPainter oldDelegate) {
    return oldDelegate.hashCode != hashCode;
  }
}
