import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class BlocModule<TBloc extends StateStreamableSource<TState>, TState>
    extends StatelessWidget {
  final TBloc Function(BuildContext context) create;
  final Widget Function(BuildContext context, TBloc bloc, TState state) child;
  final bool autoRebuild;
  final void Function(BuildContext context, TBloc bloc)? onInitialisation;
  const BlocModule({
    required this.create,
    required this.child,
    this.autoRebuild = false,
    this.onInitialisation,
    super.key,
  });

  Widget rebuildChild(BuildContext context) =>
      child(context, context.watch<TBloc>(), context.watch<TBloc>().state);
  Widget staticChild(BuildContext context) =>
      child(context, context.read<TBloc>(), context.read<TBloc>().state);

  @override
  Widget build(BuildContext context) => BlocProvider<TBloc>(
    create: (context) {
      final bloc = create(context);
      onInitialisation?.call(context, bloc);
      return bloc;
    },
    child: Builder(
      builder: (context) =>
          autoRebuild ? rebuildChild(context) : staticChild(context),
    ),
  );
}
