import 'dart:async';

import 'package:syncrow_web/pages/space_management_v2/modules/communities/domain/params/load_communities_param.dart';
import 'package:syncrow_web/pages/space_management_v2/modules/communities/domain/services/communities_service.dart';

final class DebouncedCommunitiesService implements CommunitiesService {
  DebouncedCommunitiesService(
    this._decoratee, {
    this.debounceDuration = const Duration(milliseconds: 500),
  });

  final CommunitiesService _decoratee;
  final Duration debounceDuration;

  Timer? _debounceTimer;
  late Completer<CommunitiesPaginationModel>? _completer;

  @override
  Future<CommunitiesPaginationModel> getCommunity(
    LoadCommunitiesParam param,
  ) async {
    _debounceTimer?.cancel();

    _completer = Completer<CommunitiesPaginationModel>();
    final currentCompleter = _completer!;

    _debounceTimer = Timer(debounceDuration, () async {
      try {
        final result = await _decoratee.getCommunity(param);
        if (!currentCompleter.isCompleted) {
          currentCompleter.complete(result);
        }
      } catch (error) {
        if (!currentCompleter.isCompleted) {
          currentCompleter.completeError(error);
        }
      }
    });

    return currentCompleter.future;
  }
}
