import 'dart:async';
import 'dart:collection';
import 'dart:ui';

import 'package:guru_utils/datetime/datetime_utils.dart';
import 'package:guru_utils/id/id_utils.dart';

/// Created by Haoyi on 2022/1/19

class ActiveTimer {
  final String id;
  final Duration duration;
  final int _start;
  final Timer _timer;
  final VoidCallback computation;

  ActiveTimer.create(this.duration, this.computation)
      : id = IdUtils.uuidV4(),
        _start = DateTimeUtils.currentTimeInMillis(),
        _timer = Timer(duration, computation);

  ActiveTimer.periodic(this.duration, this.computation)
      : id = IdUtils.uuidV4(),
        _start = DateTimeUtils.currentTimeInMillis(),
        _timer = Timer.periodic(duration, (timer) => computation());

  int get elapsedTime => DateTimeUtils.currentTimeInMillis() - _start;

  void _dispose() {
    _timer.cancel();
  }
}

class TimerScheduler {
  final HashMap<String, ActiveTimer> timerMap = HashMap();

  ActiveTimer delayed(Duration duration, VoidCallback callback) {
    final timer = ActiveTimer.create(duration, callback);
    timerMap[timer.id] = timer;
    return timer;
  }

  ActiveTimer periodic(Duration duration, VoidCallback callback) {
    final timer = ActiveTimer.periodic(duration, callback);
    timerMap[timer.id] = timer;
    return timer;
  }

  void removeTimer(ActiveTimer timer) {
    timerMap.remove(timer.id)?._dispose();
  }

  void disposeAll() {
    if (timerMap.isNotEmpty) {
      final timerList = timerMap.values.toList();
      for (var timer in timerList) {
        timer._dispose();
      }
      timerMap.clear();
    }
  }
}
