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

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

  bool autoRerender;
  Future Function(Map param) fetch;
  Function({PagedResult state}) useState;
  Function? onError;

  Widget Function({
    BuildContext context,
    Function toggle,
  }) 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 = [];

  @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);

      if (widget.autoRerender) {
        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
      ),
    );
  }
}