import 'dart:async';

import 'package:guru_utils/log/log.dart';

/// Created by Haoyi on 2022/7/31

class CountdownManager {
  static const _periodDuration = Duration(seconds: 1);

  late StreamController<Duration> _elapsedTimeStream;

  Stream<Duration> get observableElapsedTime => _elapsedTimeStream.stream;

  Timer? _timer;

  CountdownManager() {
    _elapsedTimeStream =
        StreamController.broadcast(onListen: _onFirstListen, onCancel: _onLastCancel);
  }

  void _onFirstListen() {
    Log.v("_onFirstListen");
    _timer = Timer.periodic(_periodDuration, (timer) {
      Log.v("timer: ${timer.isActive}");
      _elapsedTimeStream.add(_periodDuration);
    });
  }

  void _onLastCancel() {
    Log.v("_onLastCancel");
    _timer?.cancel();
  }

  void dispose() {
    _timer?.cancel();
    _elapsedTimeStream.close();
  }
}
