import 'package:flutter/material.dart';
import 'package:flut/flut/object.dart';
import 'package:flut/flut/runtime.dart';
import 'package:flut/dart/ui.dart';

class FlutCustomPainter extends CustomPainter with FlutAbstractObject {
  @override
  final FlutRuntime runtime;
  final String paintActionId;

  FlutCustomPainter._(this.runtime, this.paintActionId);

  static FlutCustomPainter? flutDecode(
    FlutRuntime runtime,
    Map<String, dynamic> data,
  ) {
    final paintActionId = runtime.unpackOptionalField<String>(
      data,
      'paintActionId',
    );
    if (paintActionId == null) return null;
    return FlutCustomPainter._(runtime, paintActionId);
  }

  @override
  void paint(Canvas canvas, Size size) {
    final oid = runtime.generateOid();
    final flutCanvas = FlutCanvas.wrap(
      runtime: runtime,
      oid: oid,
      target: canvas,
    );
    runtime.objectRegistry[oid] = flutCanvas;
    try {
      runtime.callAction(paintActionId, args: [flutCanvas, size]);
    } finally {
      runtime.objectRegistry.remove(oid);
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}
