// ignore_for_file: file_names

import 'dart:async';

import 'package:job_portal_app/Services/global_variables.dart';
import 'package:signalr_netcore/hub_connection_builder.dart';

// ignore: camel_case_types
class signalR {
  final hubConnection =
      HubConnectionBuilder().withUrl('$myUrl/NotificationHub').build();

  signalR();

  Future<void> startSignalRConnection() async {
    try {
      await hubConnection.start();
    } catch (error) {
      // ignore: avoid_print
      print("Error starting SignalR connection: $error");
    }
  }

  Future<bool> asyncInitState() async {
    await startSignalRConnection();
    return _receive();
  }

  Future<bool> asyncInitStateFromJobsseker() async {
    await startSignalRConnection();
    return _receiveFromJobseeker();
  }

  Future<bool> _receive() async {
    Completer<bool> completer = Completer<bool>();
    hubConnection.invoke("JoinGroup", args: ["companyId_${identifier.id}"]);

    onReceiveNotification(arguments) {
      hubConnection.off("ReceiveNotification");
      completer.complete(true);
    }

    hubConnection.on("ReceiveNotification", onReceiveNotification);
    return completer.future;
  }

  Future<bool> _receiveFromJobseeker() async {
    Completer<bool> completer = Completer<bool>();
    hubConnection.invoke("JoinGroup", args: ["jobseekerId_${identifier.id}"]);
    onReceiveNotification(arguments) {
      hubConnection.off("ReceiveNotification");
      completer.complete(true);
    }

    hubConnection.on("ReceiveNotification", onReceiveNotification);

    return completer.future;
  }
}
