const AgoraMiniappSDK = require("../lib/agora-miniapp-sdk.js");
const option = {
  appId: '',
  token: '',
  tokenA: '',
  channelId: '',
  screenShareId: '',
  uid: 0
}
let client: any = '';
export const agora = {
  // 初始化
  init: async () => {
    client = new AgoraMiniappSDK.Client();
    await client.init(option.appId);
  },
  // 销毁
  destroy: async () => {
    if (client) {
      await client.leave()
      await client.destroy()
      client = '';
    }
  },
  // 设置角色
  setRole: async (isRoomManager: boolean, callBack?: Function) => {
    await client.setRole(isRoomManager ? 'broadcaster' : 'audience')
    if (isRoomManager) {
      client.publish((url: string) => {
        callBack && callBack(url)
      })
    }
  },
  // 设置频道参数
  setOption: async (data) => {
    option.token = data.token;
    option.tokenA = data.tokenA;
    option.channelId = data.channelId;
    option.appId = data.appId;
    option.uid = Number(data.uid);
    option.screenShareId = data.screenShareId;
    await agora.init()
  },
  // 加入频道
  joinChannel: () => {
    client.join(option.token, option.channelId, option.uid, () => {
      agora.setRole(false)
    })
  },
  // 监听
  clientEvent: ({ streamAdded, streamRemoved }) => {
    client.on("stream-added", async e => {
      await agora.subscribe(e.uid, (url: string, uid: number | string) => {
        streamAdded(url, uid)
      })
    });
    client.on("stream-removed", async e => {
      streamRemoved(e.uid)
    });
  },
  // 订阅远端音视频流
  subscribe: async (uid: number | string, callBack: Function) => {
    const { url, rotation } = await client.subscribe(uid)
    callBack(url, uid)
  },
  // 停止发送本地音视频流
  muteLocal: async (target: string) => {
    await client.muteLocal(target)
  },
  // 恢复发送本地音视频流
  unmuteLocal: async (target: string) => {
    await client.unmuteLocal(target)
  },
}