import 'package:fis_measure/interfaces/process/items/item.dart';
import 'package:fis_measure/interfaces/process/items/item_feature.dart';
import 'package:fis_measure/interfaces/process/workspace/application.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class MeasureRecordsCanvasPanel extends StatefulWidget {
  const MeasureRecordsCanvasPanel({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _RecordsCanvasPanelState();
}

class _RecordsCanvasPanelState extends State<MeasureRecordsCanvasPanel> {
  late final application = Get.find<IApplication>();
  late List<IMeasureItemFeature> features = [];

  @override
  void initState() {
    _addListenrs();
    super.initState();
  }

  @override
  void dispose() {
    _removeListenrs();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (features.isEmpty) return const SizedBox();

    return LayoutBuilder(builder: (context, constraints) {
      return SizedBox(
        width: constraints.maxWidth,
        height: constraints.maxHeight,
        child: RepaintBoundary(
          child: CustomPaint(
            painter: _PanelPainter(features),
          ),
        ),
      );
    });
  }

  void _updateFeatures() {
    features.clear();
    for (var item in application.items) {
      features.addAll(item.measuredFeatures);
    }
  }

  void _onMeasureRerenderReady(Object sender, void e) {
    if (mounted) {
      setState(() {
        _updateFeatures();
      });
    }
  }

  void _addListenrs() {
    application.measureRerenderReady.addListener(_onMeasureRerenderReady);
  }

  void _removeListenrs() {
    application.measureRerenderReady.removeListener(_onMeasureRerenderReady);
  }
}

class _PanelPainter extends CustomPainter {
  final List<IMeasureItemFeature> features;
  _PanelPainter(this.features);

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

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