import { audio } from "@kit.AudioKit";
import { BusinessError } from "@kit.BasicServicesKit";

class AVSessionManager {
  private  audioManager = audio.getAudioManager();
  private  audioSessionManager: audio.AudioSessionManager = this.audioManager.getSessionManager();

  private strategy: audio.AudioSessionStrategy = {
    concurrencyMode: audio.AudioConcurrencyMode.CONCURRENCY_PAUSE_OTHERS
  };

  /**
   * 激活音频会话
   */
  async activate() {
    if (!this.isActive()) {
      await this.audioSessionManager.activateAudioSession(this.strategy).then(() => {
        console.info('Succeeded in activating audio session.');
      }).catch((err: BusinessError) => {
        console.error(`Failed to activate audio session. Code: ${err.code}, message: ${err.message}`);
      });
    }
  }

  /**
   * 停用音频会话
   */
  async deactivate() {
    if (this.isActive()) {
      await this.audioSessionManager.deactivateAudioSession().then(() => {
        console.info('Succeeded in deactivating audio session.');
      }).catch((err: BusinessError) => {
        console.error(`Failed to deactivate audio session. Code: ${err.code}, message: ${err.message}`);
      });
    }
  }

  /**
   * 会话是否激活
   * @returns
   */
  isActive(): boolean {
    return this.audioSessionManager.isAudioSessionActivated();
  }

  /**
   * 添加会话停用监听
   */
  setDeactivatedCallback(callback: Callback<audio.AudioSessionDeactivatedEvent>) {
    this.audioSessionManager.on('audioSessionDeactivated', callback);
  }

  /**
   * 移除会话停用监听
   */
  removeDeactivatedCallback(callback?: Callback<audio.AudioSessionDeactivatedEvent>) {
    this.audioSessionManager.off('audioSessionDeactivated', callback);
  }
}

export const avSessionManager = new AVSessionManager()