import 'dart:async';

import 'package:chat/data/constants.dart';
import 'package:connectivity/connectivity.dart';

import 'NetUtil.dart';

class NetStateBloc {
  Connectivity _connectivity = Connectivity();

  ConnectivityResult lastNet;
  StreamController<int> _streamController = StreamController<int>.broadcast();
  Stream<int> get stream => _streamController.stream;

  void start() {
    _connectivity.onConnectivityChanged.listen(_updateConnectionStatus);
  }

  _updateConnectionStatus(ConnectivityResult result) async {
    print('网络状态改变$result');
    if (result == ConnectivityResult.none) {
      lastNet = result;
      _streamController.sink.add(ChatState.connecting.index);
    } else {
      if (lastNet != result) {
        lastNet = result;
        if (NetWork().isInit && !NetWork().isConnecting) {
          NetWork().reconnect();
        }
      }
    }
  }

  addState(ChatState state) {
    _streamController.sink.add(state.index);
  }

  void dispose() {
    _streamController.close();
  }
}
