

import 'package:flutter/cupertino.dart';

/// Event system

class ListenerReceipt<T> {
  Function(T) listener;

  ListenerReceipt(this.listener);
}

class EventDelegate<T> {
  final List<ListenerReceipt<T>> _receipts = [];

  ListenerReceipt<T> addListener(Function(T) listener) {
    final receipt = ListenerReceipt(listener);
    _receipts.add(receipt);
    return receipt;
  }

  void removeListener(ListenerReceipt<T> receipt) {
    _receipts.remove(receipt);
    print("removed listener");
  }

  void trigger(T event) {
    print("triggering event");
    for (var receipt in _receipts) {
      print("triggering listener");
      try {
        receipt.listener(event);
      } catch (e) {
        print("Error in listener: $e");
        removeListener(receipt);
      }
    }
  }
}

// flutter integration

class DelegateBuilder<T> extends StatefulWidget {
  final EventDelegate<T> delegate;
  final Widget Function(BuildContext, T) builder;
  final Widget Function(BuildContext)? defaultBuilder;

  DelegateBuilder({required this.delegate, required this.builder, this.defaultBuilder}) : super(key: UniqueKey())
  {
    print("created delegate builder widget");
  }

  @override
  State<StatefulWidget> createState() => _DelegateBuilderState<T>();


}

class _DelegateBuilderState<T> extends State<DelegateBuilder<T>> {
  late ListenerReceipt<T> _receipt;

  T? lastEvent;

  @override
  void initState() {
    super.initState();
    print("init delegate builder widget");
    _receipt = widget.delegate.addListener((event) {
      lastEvent = event;
      print("triggered");
      setState(() {

      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    widget.delegate.removeListener(_receipt);
    print("disposed");
  }

  @override
  Widget build(BuildContext context) {
    print("rebuilt");
    print("Valid: ${lastEvent != null}");
    return lastEvent == null ? widget.defaultBuilder == null ? Container() : widget.defaultBuilder!(context) : widget.builder(context, lastEvent!);
  }
}