
import 'package:flutter/material.dart';
import 'package:twong/utils/index.dart';

class FutureWidget extends StatefulWidget {
  final PreferredSize appbar;
  final Future<dynamic> Function({dynamic data}) future;
  final Widget error;
  final Widget loading;
  final dynamic data;
  final Widget Function(dynamic) bodyBuilder;

  FutureWidget(this.future, this.bodyBuilder, {Key key, this.appbar, this.loading, this.error, this.data }): super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _FutureWidgetState();
  }
}

class _FutureWidgetState extends State<FutureWidget> {
  dynamic _data;
  Future _future;

  @override
  void initState() {
    super.initState();
    // initData();
    _future = widget.future(data: widget.data);
  }

  initData() async {
    var data = await widget.future(data: widget.data);
    setState(() {
      _data = data;
    });
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(future: _future, builder: _buildFuture, initialData: {});
  }

  Widget _buildFuture (BuildContext context, AsyncSnapshot snapshot) {
    switch (snapshot.connectionState) {
      case ConnectionState.none:
        return Center(child: Text("none"));
      case ConnectionState.active:
        return Center(child: Text("active"));
      case ConnectionState.waiting:
        return widget.loading == null ? Center(child: CircularProgressIndicator()) : widget.loading;
      case ConnectionState.done:
        if (snapshot.hasError) {
          Log.e("Future Error: ${snapshot.error}");
          return widget.loading == null ? Center(child: Text(snapshot.error.toString())) :widget.error;
        } else {
          return widget.bodyBuilder(snapshot.data);
        }
    }
    return Container();
  }
}