import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import 'package:guru_utils/extensions/extensions.dart';
import 'package:guru_utils/timer/timer_scheduler.dart';

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

class BaseController extends GetxController {
  final CompositeSubscription subscriptions = CompositeSubscription();

  final TimerScheduler timerScheduler = TimerScheduler();

  BaseController();

  void addSubscription(StreamSubscription? subscription) {
    if (subscription != null && !subscriptions.isDisposed) {
      subscriptions.add(subscription);
    }
  }

  void disposeSubscriptions() {
    if (!subscriptions.isDisposed) {
      subscriptions.dispose();
    }
  }

  ActiveTimer delayed(Duration duration, VoidCallback callback) {
    return timerScheduler.delayed(duration, callback);
  }

  ActiveTimer periodic(Duration duration, VoidCallback callback) {
    return timerScheduler.periodic(duration, callback);
  }

  void removeTimer(ActiveTimer? timer) {
    if (timer != null) {
      timerScheduler.removeTimer(timer);
    }
  }

  @override
  @mustCallSuper
  void onClose() {
    disposeSubscriptions();
    timerScheduler.disposeAll();
    super.onClose();
  }

  @override
  @mustCallSuper
  void onReady() {
    super.onReady();
  }

  @override
  @mustCallSuper
  void onInit() {
    super.onInit();
  }
}
