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 MeasureItemCanvas extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _MeasureItemCanvasState();
}

class _MeasureItemCanvasState extends State<MeasureItemCanvas> {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

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

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

class _ActiveCanvasPanelState extends State<MeasureActiveCanvasPanel> {
  late final application = Get.find<IApplication>();
  IMeasureItemFeature? feature;

  @override
  void initState() {
    feature = application.activeItem?.feature;
    _addListenrs();
    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    if (feature == null) return const SizedBox();
    return LayoutBuilder(builder: (context, constraints) {
      return SizedBox(
        width: constraints.maxWidth,
        height: constraints.maxHeight,
        child: RepaintBoundary(
          child: CustomPaint(
            painter: _PanelPainter(feature!),
          ),
        ),
      );
    });
  }

  void _onMeasureRerenderReady(Object sender, void e) {
    if (mounted) {
      setState(() {
        feature = application.activeItem?.feature;
      });
    }
  }

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

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

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

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

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