import 'package:flutter/material.dart';
import 'package:flyinsono/lab/pages/lab_image/widgets/image_measure_overlay/controller.dart';
import 'package:fis_measure/interfaces/process/items/item_feature.dart';
import 'package:fis_measure/process/workspace/urm/application.dart';
import 'package:get/get.dart';

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

  @override
  String? get tag => tabHashCode;

  final String tabHashCode;

  @override
  Widget build(BuildContext context) {
    return GetBuilder<ImageMeasureOverlayController>(
      tag: tabHashCode,
      id: ImageMeasureOverlayController.activeCanvasLayerId,
      builder: (_) {
        if (controller.app == null) return const SizedBox();
        final feature = controller.app!.activeMeasureItem?.feature;
        if (feature == null) return const SizedBox();
        if (controller.app! is URMApplication) {
          Rect? zoomRect = (controller.app as URMApplication)
              .urmDataProcessor
              .measureAreaInFullVisual;
          feature.setZoomRect(zoomRect);
        }
        return LayoutBuilder(
          builder: (context, constraints) {
            return ClipRect(
              child: SizedBox(
                width: constraints.maxWidth,
                height: constraints.maxHeight,
                child: RepaintBoundary(
                  child: CustomPaint(
                    painter: _PanelPainter(feature),
                  ),
                ),
              ),
            );
          },
        );
      },
    );
  }
}

class _PanelPainter extends CustomPainter {
  final IMeasureItemFeature feature;
  _PanelPainter(this.feature);

  @override
  void paint(Canvas canvas, Size size) {
    if (feature.checkCanPaint()) {
      feature.paint(canvas, size);
    }
  }

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