import { createGlobalState, useDevicesList } from '@vueuse/core'

export const useDevices = createGlobalState(() => {
  const {
    ensurePermissions,
    permissionGranted,
    videoInputs,
    audioInputs,
    audioOutputs,
  } = useDevicesList()

  async function getShareStream(fps = 30, resolution = 1080) {
    return navigator.mediaDevices.getDisplayMedia({
      audio: false,
      video: {
        height: { max: resolution },
        displaySurface: 'monitor',
        frameRate: { ideal: fps, max: fps },
      },
    })
  }

  ;(async () => {
    if (permissionGranted.value)
      return

    await ensurePermissions()
  })()

  return {
    ensurePermissions,
    permissionGranted,
    videoInputs: computed<MediaDeviceInfo[]>(() => JSON.parse(JSON.stringify(videoInputs.value))),
    audioInputs: computed<MediaDeviceInfo[]>(() => JSON.parse(JSON.stringify(audioInputs.value))),
    audioOutputs: computed<MediaDeviceInfo[]>(() => JSON.parse(JSON.stringify(audioOutputs.value))),
    getShareStream,
  }
})
