import 'dart:convert'; import 'package:wanisclient/providers/utils_singleton.dart'; import 'package:pubnub/pubnub.dart'; import 'dart:convert'; import 'package:pubnub/pubnub.dart'; import '../../config/constants/app_constant.dart'; // ► put your real keys here (same ones as the Android app) const String publishKey = 'pub-key-from-dashboard'; const String subscribeKey = 'sub-key-from-dashboard'; // The dispatcher that sends offers final PubNub dispatcher = PubNub( defaultKeyset: Keyset( publishKey: publishKey, subscribeKey: subscribeKey, userId: const UserId('dispatcher'), // anything, doesn’t matter here ), ); /// Push an offer that *only* driverUsername should receive. Future sendRideOffer({ required int rideId, required String driverUsername, String message = 'New ride request', }) async { final payload = { 'rideId': rideId, 'candidateUsernames': [driverUsername], // <- MATCHES the Java “username” 'message': message, }; // Publish as *raw* JSON string, exactly what the Android code expects await dispatcher.channel('offers.drivers').publish(jsonEncode(payload)); print('Offer $rideId sent to $driverUsername'); } class PubNubService { // ——— Singleton boiler-plate ———————————————————————————————— static final PubNubService _instance = PubNubService._internal(); factory PubNubService() => _instance; PubNubService._internal() { _pubnub = PubNub( defaultKeyset: Keyset( publishKey: pubKey, subscribeKey: subKey, userId: UserId('${utils.user!.username}'), ), ); } // ——— Internal state ———————————————————————————————————————— late final PubNub _pubnub; Subscription? _subscription; /// Inbound messages from whatever channels you subscribe to. Stream get inboundStream => _subscription!.messages; /// Subscribe to a **set** of channels. /// Call again to change channels (previous sub is disposed automatically). void subscribeTo(Set channels) { _subscription?.dispose(); _subscription = _pubnub.subscribe(channels: channels); _subscription!.messages.listen((envelope) { print('🛈 [PubNub] MSG on ${envelope.channel} ⇢ ${envelope.payload}'); }); print('✅ [PubNub] Subscribed to $channels'); } /// Publish **any JSON-encodable object**. /// Will be encoded with `jsonEncode`. Future publishJson(String channel, Object payload) async { final encoded = jsonEncode(payload); print('⏫ [PubNub] PUBLISH → $channel : $encoded'); await _pubnub.channel(channel).publish(encoded); } /// Publish a **plain string** (no extra JSON encoding). Future publishString(String channel, String text) async { print('⏫ [PubNub] PUBLISH → $channel : $text'); await _pubnub.channel(channel).publish(text); } /// Dispose when your app leaves / logs out. Future dispose() async { await _subscription?.dispose(); print('🛑 [PubNub] disposed'); } }