import 'package:dartin/dartin.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

/// Provider封装类
///
/// 方便数据初始化
class ProviderWidget<T extends ChangeNotifier, S> extends StatefulWidget {
  final ValueWidgetBuilder<S> builder;
  final S Function(BuildContext, T) selector;
  final T model;
  final Widget child;
  final Function(T model) onModelReady;
  final bool autoDispose;
  final ShouldRebuild<S> shouldRebuild;

  ProviderWidget({
    Key key,
    @required this.builder,
    @required this.selector,
    this.model,
    this.child,
    this.onModelReady,
    this.autoDispose: true,
    this.shouldRebuild,
  }) : super(key: key);

  _ProviderWidgetState<T, S> createState() => _ProviderWidgetState<T, S>();
}

class _ProviderWidgetState<T extends ChangeNotifier, S> extends State<ProviderWidget<T, S>> {
  T model;

  @override
  void initState() {
    model = widget.model ?? inject();
    widget.onModelReady?.call(model);
    super.initState();
  }

  @override
  void dispose() {
    if (widget.autoDispose) model.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<T>.value(
      value: model,
      child: Selector<T, S>(
        selector: widget.selector,
        builder: widget.builder,
        child: widget.child,
        shouldRebuild: widget.shouldRebuild,
      ),
    );
  }
}
