import 'dart:async';


class AutoRefreshScheduler {
  bool _enabled = true;
  Timer? _timer;
  DateTime? _scheduledAt;
  DateTime? _triggeredAt;

  void setEnabled(bool enabled) {
    if (_enabled == enabled) return;
    _enabled = enabled;
    if (!enabled) {
      _clear();
    }
  }

  void sync({
    required bool isLoading,
    required bool canRefresh,
    required DateTime? scheduledAt,
    required Future<void> Function() onRefresh,
  }) {
    if (!_enabled || isLoading || !canRefresh) {
      _clear();
      return;
    }

    if (scheduledAt == null) {
      _clear();
      return;
    }

    final delay = scheduledAt.difference(DateTime.now().toUtc());
    if (delay <= Duration.zero) {
      if (_triggeredAt != null && _triggeredAt!.isAtSameMomentAs(scheduledAt)) {
        return;
      }
      _triggeredAt = scheduledAt;
      _clearTimer();
      onRefresh();
      return;
    }

    if (_scheduledAt != null &&
        _scheduledAt!.isAtSameMomentAs(scheduledAt) &&
        _timer?.isActive == true) {
      return;
    }

    _triggeredAt = null;
    _clearTimer();
    _scheduledAt = scheduledAt;
    _timer = Timer(delay, () {
      onRefresh();
    });
  }

  void reset() {
    _enabled = false;
    _clear();
  }

  void dispose() {
    _clear();
  }

  void _clear() {
    _scheduledAt = null;
    _triggeredAt = null;
    _clearTimer();
  }

  void _clearTimer() {
    _timer?.cancel();
    _timer = null;
  }
}
