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

///页面刷新通知
class BaseChangeNotifier extends ChangeNotifier {
  StreamController pageController = StreamController.broadcast();

  ///刷新通知方法
  void refresh() {
    pageController.add("refresh");
    notifyListeners();
  }

  void close() {
    pageController.close();
  }

  Stream get stream => pageController.stream;

}

enum EventType {
  refresh,

  ///刷新事件
}

///页面刷新辅助类
class RefreshListener {
  bool isListen = false;
  StreamSubscription streamSubscription;

  ///监听方法
  ///已废弃
  void _listen(BuildContext context, Function(String) refresh) {
    BaseChangeNotifier baseChangeNotifier;
    try {
      baseChangeNotifier = Provider.of<BaseChangeNotifier>(context);
    } catch (e, s) {
      print(e);
      print(s);
      throw Exception(
          "父页面或父控件必须添加 BaseChangeNotifier 的 Provide值才能使用RefreshListener对象");
    }
    if (!isListen && baseChangeNotifier != null) {
      isListen = true;
      streamSubscription = baseChangeNotifier.stream.listen((event) {
        if (refresh != null) {
          refresh(event);
        }
      });
    }
  }

  ///监听构造
  RefreshListener.listen(BuildContext context, Function(String) refresh) {
    BaseChangeNotifier baseChangeNotifier;
    try {
      baseChangeNotifier = Provider.of<BaseChangeNotifier>(context);
    } catch (e, s) {
      print(e);
      print(s);
      throw Exception(
          "父页面或父控件必须添加 BaseChangeNotifier 的 Provide值才能使用RefreshListener对象");
    }
    if (!isListen && baseChangeNotifier != null) {
      isListen = true;
      baseChangeNotifier.stream.listen((event) {
        if (refresh != null) {
          refresh(event);
        }
      });
    }
  }

  ///关闭监听
  void close() {
    if (streamSubscription != null) {
      streamSubscription.cancel();
    }
  }
}