"use strict";

import AsyncStorage from '@react-native-async-storage/async-storage';
import { subscribeToPushNotifications } from '../networking/api-requests/push.api';
import { subscribeToRoomMessages } from '../networking/xmpp/subscribeToRoomMessages.xmpp';
const SUBSCRIBED_ROOMS_KEY = 'ethora_subscribed_rooms';
export class PushSubscriptionService {
  subscribedRooms = new Set();
  isPushSubscribed = false;
  lastSubscriptionKey = null;
  isInitialized = false;
  async loadSubscribedRoomsFromStorage() {
    if (this.isInitialized) {
      return;
    }
    try {
      const storedRooms = await AsyncStorage.getItem(SUBSCRIBED_ROOMS_KEY);
      if (storedRooms) {
        const roomsArray = JSON.parse(storedRooms);
        this.subscribedRooms = new Set(roomsArray);
      }
      this.isInitialized = true;
    } catch (error) {
      console.error('[PushService] Failed to load subscribed rooms from storage:', error);
    }
  }
  async saveSubscribedRoomsToStorage() {
    try {
      const roomsArray = Array.from(this.subscribedRooms);
      await AsyncStorage.setItem(SUBSCRIBED_ROOMS_KEY, JSON.stringify(roomsArray));
    } catch (error) {
      console.error('[PushService] Failed to save subscribed rooms to storage:', error);
    }
  }
  async subscribeToPush(fcmToken, user, projectName) {
    const walletAddress = user.defaultWallet?.walletAddress || user.walletAddress;
    const subscriptionKey = `${fcmToken}_${walletAddress}`;
    if (this.isPushSubscribed && this.lastSubscriptionKey === subscriptionKey) {
      console.log('⚠️ Push already subscribed with this token, skipping...');
      return;
    }
    try {
      const userJid = user.xmppUsername || '';
      if (!userJid) {
        throw new Error('User JID is required for push subscription');
      }
      await subscribeToPushNotifications(fcmToken, userJid, projectName);
      this.isPushSubscribed = true;
      this.lastSubscriptionKey = subscriptionKey;
    } catch (error) {
      console.error('Failed to subscribe to push after all retries:', error);
    }
  }
  async subscribeToRoom(client, roomJID, userNick) {
    await this.loadSubscribedRoomsFromStorage();
    if (this.subscribedRooms.has(roomJID)) {
      return true;
    }
    try {
      const result = await subscribeToRoomMessages(client, roomJID, userNick);
      if (result) {
        this.subscribedRooms.add(roomJID);
        await this.saveSubscribedRoomsToStorage();
      }
      console.log('Successfully Subscribed to room', roomJID);
      return result;
    } catch (error) {
      console.error(`[PushService] Failed to subscribe to room ${roomJID}:`, error);
      return false;
    }
  }
  async subscribeToRooms(client, roomJIDs, userNick) {
    let successful = 0;
    let failed = 0;
    console.log('test roomJIDs', roomJIDs);
    for (const roomJID of roomJIDs) {
      try {
        const result = await this.subscribeToRoom(client, roomJID, userNick);
        console.log('test roomJID-1', result);
        if (result) {
          successful++;
        } else {
          failed++;
        }
        await new Promise(resolve => setTimeout(resolve, 100));
      } catch (error) {
        failed++;
        console.error(`Failed to subscribe to room ${roomJID}:`, error);
      }
    }
    console.log(`Subscribed to ${successful} rooms, ${failed} failed`);
  }
  async reset() {
    this.subscribedRooms.clear();
    this.isPushSubscribed = false;
    this.lastSubscriptionKey = null;
    this.isInitialized = false;
    try {
      await AsyncStorage.removeItem(SUBSCRIBED_ROOMS_KEY);
      console.log('[PushService] Subscribed rooms cleared from storage');
    } catch (error) {
      console.error('[PushService] Failed to clear subscribed rooms from storage:', error);
    }
  }
  isRoomSubscribed(roomJID) {
    return this.subscribedRooms.has(roomJID);
  }
  getSubscribedRooms() {
    return Array.from(this.subscribedRooms);
  }
}
export const pushSubscriptionService = new PushSubscriptionService();
//# sourceMappingURL=pushSubscriptionService.js.map