
import 'package:farmer_client/models/entities/PagedResult.dart';
import 'package:flutter/material.dart';

class RefreshBuilder extends StatefulWidget {
  RefreshBuilder({
    Key? key,
    required this.builder,
    required this.fetch,
    required this.useState,
    this.onError,
  }): super(key: key);

  Future Function(Map param) fetch;
  Function({PagedResult state, void Function(VoidCallback) setState}) useState;
  Function? onError;

  Widget Function({
    BuildContext context,
    Widget Function(Widget) reactor,
    Function toggle,
    PagedResult Function() result,
    List<dynamic> listData,
  }) builder;

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

class _RefresherState extends State<RefreshBuilder> {

  PagedResult result = PagedResult(total: 0, size: 0, pages: 0, current: 0);
  List<dynamic> listData = [];
  void Function(void Function())? _subSetState;

  @override
  initState() {
    super.initState();
    fetchData();
  }

  Future fetchData() {
    return Future.value(widget.fetch({ "pageNum": 1 }).then((res) {
      final pagedResult = PagedResult.fromJson(res);
      widget.useState(state: pagedResult, setState: setState);
    }).catchError((err) {
      print(err);
      if (null != widget.onError) {
        widget.onError!(err);
      }
    }));
  }

  toggle() {
    fetchData();
  }

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
      triggerMode: RefreshIndicatorTriggerMode.onEdge,
      onRefresh: fetchData,
      child: widget.builder(
          context: context,
          toggle: toggle
      ),
    );
  }
}