/**
 * 获取已经连接的设备id
 * @param label 设备label
 */
export async function getConnectDeviceId(label = 'Slave') {
  // 申请权限
  await applyPermission()
  // 获取当前设备
  const devices = await navigator.mediaDevices.enumerateDevices()
  // 取出当前需要展示的数据
  const filtered = devices.find(device => device.label.indexOf(label) >= 0)
  console.log('当前已连接的设备：', devices)
  // 获取当前设备id
  return filtered ? filtered.deviceId : ''
}

const PERMISSION = {
  VIDEO_AUDIO: 'VIDEO_AUDIO',
  VIDEO: 'VIDEO',
  AUDIO: 'AUDIO'
}

/**
 * 申请权限
 * @param permissionCode 权限码
 */
export async function applyPermission(permissionCode = PERMISSION.VIDEO_AUDIO) {
  // 检测是否是第一次打开
  const notFirstIn = localStorage.getItem('not-first-inf')
  // 如果是第一次打开，则拉起是否打开视频的确认框
  if (notFirstIn) {
    return
  }
  // 媒体参数
  const constraints = {}
  // 判断权限码
  switch (permissionCode) {
    case PERMISSION.AUDIO:
      constraints['audio'] = true
      break
    case PERMISSION.VIDEO:
      constraints['video'] = true
      break
    case PERMISSION.VIDEO_AUDIO:
      constraints['video'] = true
      constraints['audio'] = true
      break
  }
  // 申请权限
  await navigator.mediaDevices.getUserMedia(constraints)
  // 标记当前非第一次打开
  localStorage.setItem('not-first-inf', 'true')
}
