import 'dart:async';
import 'package:flutter/widgets.dart';

class _OneShotResumeObserver with WidgetsBindingObserver {
  _OneShotResumeObserver(this._onResume);
  final Future<void> Function() _onResume;
  bool _done = false;

  void start() => WidgetsBinding.instance.addObserver(this);
  void stop() {
    if (_done) return;
    _done = true;
    WidgetsBinding.instance.removeObserver(this);
  }

  @override
  Future<void> didChangeAppLifecycleState(AppLifecycleState state) async {
    if (state == AppLifecycleState.resumed && !_done) {
      try {
        await _onResume();
      } finally {
        stop();
      }
    }
  }
}

Future<void> waitRecheckOnNextResume(
  Future<void> Function() onResume, {
  Duration timeout = const Duration(seconds: 45),
}) async {
  final c = Completer<void>();
  final obs = _OneShotResumeObserver(() async {
    try {
      await onResume();
    } finally {
      if (!c.isCompleted) c.complete();
    }
  })..start();

  Future.delayed(timeout, () {
    obs.stop();
    if (!c.isCompleted) c.complete();
  });

  return c.future;
}
