import 'package:flutter/material.dart';

import '../../exceptions/api_exception.dart';

/// ## Change Notifier Class To Handle The State While Waiting The Futures Value
class LoadingNotifier with ChangeNotifier {
  bool _loading = false;

  /// - Returns [TRUE] if [waitApiRequest] function called
  /// - Returns [FALSE] if [waitApiRequest] function completed in both states (failed, succeed)
  bool get loading => _loading;

  /// - [fun] : Callback function that contains the API request.
  /// - [onError] : Optional callback function to handle the request on failure with [APIException] parameter.
  /// - [onSuccess] : Optional callback function to handle the request on succeed.
  void waitApiRequest(Function fun, {Function(APIException)? onError, Function? onSuccess}) async {
    if (_loading == true) {
      debugPrint('loading_notifier.dart : another action already started');
      return;
    }
    _loading = true;
    debugPrint('loading_notifier.dart : start loading');
    notifyListeners();
    try {
      await fun();
      if (onSuccess != null) {
        await onSuccess();
      }
    } on APIException catch (error) {
      debugPrint("loading_notifier.dart : [_waitResult] returns this message ${error.message} : ${error.arguments}");
      if (onError != null) {
        await onError(error);
      }
    } finally {
      stopLoading();
      debugPrint('loading_notifier.dart : stop loading');
    }
  }

  /// ## Stop loading and Notify listeners
  void stopLoading() {
    _loading = false;
    notifyListeners();
  }
}
