import { PushNotifications } from '@capacitor/push-notifications';

/**
 * 推送通知服务
 * 封装了 Capacitor 推送通知插件的常用功能
 */
class PushNotificationService {
  static instance = null; // 单例实例
  isListening = false; // 标记是否已注册监听器

  constructor() {
    if (PushNotificationService.instance) {
      return PushNotificationService.instance;
    }
    PushNotificationService.instance = this;
  }

  /**
   * 获取单例实例
   */
  static getInstance() {
    if (!PushNotificationService.instance) {
      PushNotificationService.instance = new PushNotificationService();
    }
    return PushNotificationService.instance;
  }

  /**
   * 初始化并添加所有推送通知监听器。
   * 这个方法应该在应用启动时调用一次。
   *
   * @param {function} [onRegistrationSuccess] - 可选回调函数，当注册成功并获取到 token 时执行。
   * @param {function} [onRegistrationError] - 可选回调函数，当注册失败时执行。
   * @param {function} [onNotificationReceived] - 可选回调函数，当收到推送通知时执行。
   * @param {function} [onNotificationActionPerformed] - 可选回调函数，当用户与通知交互时执行。
   */
  async initialize(
    onRegistrationSuccess,
    onRegistrationError,
    onNotificationReceived,
    onNotificationActionPerformed
  ) {
    if (this.isListening) {
      console.warn('PushNotificationService listeners already initialized.');
      return;
    }

    try {
      // 添加注册监听器
      await PushNotifications.addListener('registration', (token) => {
        console.info('PushNotificationService: Registration token received', token.value);
        if (onRegistrationSuccess) {
          onRegistrationSuccess(token);
        }
      });

      await PushNotifications.addListener('registrationError', (error) => {
        console.error('PushNotificationService: Registration error', error);
        if (onRegistrationError) {
          onRegistrationError(error);
        } else {
          // 如果没有提供错误回调，则抛出，确保问题被发现
          throw new Error(`PushNotificationService Registration Error: ${error.error}`);
        }
      });

      // 添加通知事件监听器
      await PushNotifications.addListener('pushNotificationReceived', (notification) => {
        console.log('PushNotificationService: Notification received', notification);
        if (onNotificationReceived) {
          onNotificationReceived(notification);
        }
      });

      await PushNotifications.addListener('pushNotificationActionPerformed', (notification) => {
        console.log('PushNotificationService: Notification action performed', notification);
        if (onNotificationActionPerformed) {
          onNotificationActionPerformed(notification);
        }
      });

      this.isListening = true;
      console.log('PushNotificationService: All listeners registered successfully.');

    } catch (e) {
      console.error('PushNotificationService: Failed to initialize listeners', e);
      throw e; // 抛出错误以便调用方处理
    }
  }

  /**
   * 请求并注册推送通知权限。
   * 这个方法通常在用户同意后或者应用启动时调用。
   *
   * @returns {Promise<void>} 如果成功注册，则解析；如果用户拒绝或发生错误，则拒绝。
   */
  async registerForPushNotifications() {
    console.log('PushNotificationService: Checking and requesting permissions...');
    let permStatus = await PushNotifications.checkPermissions();

    if (permStatus.receive === 'prompt') {
      permStatus = await PushNotifications.requestPermissions();
    }

    if (permStatus.receive !== 'granted') {
      console.error('PushNotificationService: User denied push notification permissions.');
      throw new Error('User denied push notification permissions!');
    }

    console.log('PushNotificationService: Permissions granted. Registering...');
    await PushNotifications.register();
    console.log('PushNotificationService: Successfully registered for push notifications.');
  }

  /**
   * 获取已发送到设备并仍在通知中心的通知列表。
   *
   * @returns {Promise<Array>} 已送达通知的列表。
   */
  async getDeliveredNotifications() {
    console.log('PushNotificationService: Getting delivered notifications...');
    const notificationList = await PushNotifications.getDeliveredNotifications();
    console.log('PushNotificationService: Delivered notifications', notificationList.notifications);
    return notificationList.notifications;
  }

  /**
   * 移除所有已送达的通知。
   */
  async removeAllDeliveredNotifications() {
    console.log('PushNotificationService: Removing all delivered notifications...');
    await PushNotifications.removeAllDeliveredNotifications();
    console.log('PushNotificationService: All delivered notifications removed.');
  }

  /**
   * 移除一个或多个已送达的通知。
   * @param {Array<string>} ids - 待移除通知的 ID 数组。
   */
  async removeDeliveredNotifications(ids) {
    if (!ids || ids.length === 0) {
      console.warn('PushNotificationService: No IDs provided to removeDeliveredNotifications.');
      return;
    }
    console.log('PushNotificationService: Removing delivered notifications with IDs:', ids);
    await PushNotifications.removeDeliveredNotifications({ ids: ids });
    console.log('PushNotificationService: Specified delivered notifications removed.');
  }
}

// 导出单例实例
export const pushNotificationService = PushNotificationService.getInstance();