import 'dart:async';
import 'async_typeof.dart';

class CancelableFuture<T> implements Future<T> {
  final Completer<T> _completer = Completer<T>();

  final Cancelable? _cancelable;

  CancelableFuture(FutureCompleter<T> completer, this._cancelable) {
    completer.call(_completer);
  }

  void cancel() {
    _cancelable?.call();
  }

  @override
  Stream<T> asStream() => _completer.future.asStream();

  @override
  Future<T> catchError(Function onError, {bool Function(Object error)? test}) =>
      _completer.future.catchError(onError, test: test);

  @override
  Future<R> then<R>(FutureOr<R> Function(T value) onValue,
          {Function? onError}) =>
      _completer.future.then(onValue, onError: onError);

  @override
  Future<T> timeout(Duration timeLimit, {FutureOr<T> Function()? onTimeout}) =>
      _completer.future.timeout(timeLimit, onTimeout: onTimeout);

  @override
  Future<T> whenComplete(FutureOr<void> Function() action) =>
      _completer.future.whenComplete(action);
}

extension CancelableFutureExtension<T> on Future<T> {
  CancelableFuture<T> asCancelable(
      FutureCompleter completer, Cancelable? cancelable) {
    return CancelableFuture(completer, cancelable);
  }
}
