
//
// Copyright (c) 2013-2021 Winlin
//
// SPDX-License-Identifier: MIT
//
// https://192.168.2.7:8080/rtc/v1/publish/
'use strict'
const baseUrl = window.GyConfig.baseUrl
export function SrsError (name, message) {
  this.name = name
  this.message = message
  this.stack = (new Error()).stack
}
SrsError.prototype = Object.create(Error.prototype)
SrsError.prototype.constructor = SrsError
function _getTid () {
  return Number(parseInt(new Date().getTime() * Math.random() * 100)).toString(16).slice(0, 7)
}
// Depends on adapter-7.4.0.min.js from https://github.com/webrtc/adapter
// Async-awat-prmise based SRS RTC Publisher.
export function SrsRtcPublisherAsync () {
  const self = {
  }

  // https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia
  self.constraints = {
    audio: true,
    video: {
      width: { ideal: 1920, max: 1920 }
    }
  }
  self.audioContext = new AudioContext()
  self.mixedOutput = self.audioContext.createMediaStreamDestination()
  self.muted = function (mute) {
    const audioTracks = self.mixedOutput.stream.getAudioTracks()

    audioTracks.forEach(track => {
      track.enabled = mute
    })
  }
  /**
   *开始推流
   * @param {String} url 推流地址
   * @param {{micro:Boolean}} param1 {micro:false}默认是否静音
   * @returns
   */
  self.publish = async function (url, {
    micro
    // screen
  }) {
    self.pc.addTransceiver('video', { direction: 'sendonly' })
    self.pc.addTransceiver('audio', { direction: 'sendonly' })
    if (!navigator.mediaDevices && window.location.protocol === 'http:' && window.location.hostname !== 'localhost') {
      throw new SrsError('HttpsRequiredError', 'Please use HTTPS or localhost to publish, read https://github.com/ossrs/srs/issues/2762#issuecomment-983147576')
    }
    // const stream = await navigator.mediaDevices.getUserMedia(self.constraints)
    let stream = null
    let stream2 = null
    stream = await navigator.mediaDevices.getDisplayMedia({
      audio: true,
      video: {
        width: { ideal: 1920, max: 1920 }
      }
    })
    try {
      stream2 = await navigator.mediaDevices.getUserMedia({
        audio: true,
        video: false
      })
    } catch (error) {
      if (error instanceof DOMException) {
        if (error.name === 'NotFoundError') {
          console.info(error)
        }
      }
      stream2 = null
    }

    // 多轨音频融合
    self.audioContext = new AudioContext()
    self.mixedOutput = self.audioContext.createMediaStreamDestination()
    if (stream.getAudioTracks().length > 0) {
      const localMicrophoneStreamNode = self.audioContext.createMediaStreamSource(stream)
      localMicrophoneStreamNode.connect(self.mixedOutput)
    }
    if (stream2 && stream2.getAudioTracks().length > 0) {
      const localMicrophoneStreamNode2 = self.audioContext.createMediaStreamSource(stream2)
      localMicrophoneStreamNode2.connect(self.mixedOutput)
    }
    self.muted(micro)
    // stream2.getTracks().forEach(function (track) {
    //   // stream.addTrack(track)
    //   self.pc.addTrack(track)
    //   self.ontrack && self.ontrack({ track })
    // })
    const screenStream = new MediaStream()
    const videoTrack = stream.getVideoTracks()
    const audioTrack = self.mixedOutput.stream.getTracks()
    if (videoTrack.length > 0) { screenStream.addTrack(videoTrack[0]) }
    if (audioTrack.length > 0) {
      screenStream.addTrack(audioTrack[0])
    }

    screenStream.getTracks().forEach(function (track) {
      self.pc.addTrack(track)
      // Notify about local track when stream is ok.
      self.ontrack && self.ontrack({ track })
    })

    const offer = await self.pc.createOffer()

    await self.pc.setLocalDescription(offer)
    const session = await new Promise(function (resolve, reject) {
      // @see https://github.com/rtcdn/rtcdn-draft
      const data = {
        api: baseUrl + '/rtc/v1/publish/',
        tid: _getTid(),
        streamurl: url,
        clientip: null,
        sdp: offer.sdp
      }

      const xhr = new XMLHttpRequest()
      xhr.onload = function () {
        if (xhr.readyState !== xhr.DONE) return
        if (xhr.status !== 200) return reject(xhr)
        const data = JSON.parse(xhr.responseText)

        return data.code ? reject(xhr) : resolve(data)
      }
      xhr.open('POST', data.api, true)
      xhr.setRequestHeader('Content-type', 'application/json')
      xhr.send(JSON.stringify(data))
    })

    await self.pc.setRemoteDescription(
      new RTCSessionDescription({ type: 'answer', sdp: session.sdp })
    )

    // session.simulator = conf.schema + '//' + conf.urlObject.server + ':' + conf.port + '/rtc/v1/nack/'

    return session
  }

  // Close the publisher.
  self.close = function () {
    self.pc && self.pc.close()
    self.pc = null
  }

  // The callback when got local stream.
  // @see https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/addStream#Migrating_to_addTrack
  self.ontrack = function (event) {
    // Add track to stream of SDK.
    self.stream.addTrack(event.track)
  }

  // Internal APIs.

  self.pc = new RTCPeerConnection(null)
  self.stream = new MediaStream()

  return self
}

export function SrsRtcPlayerAsync () {
  const self = {}
  self.play = async function (url) {
    self.pc.addTransceiver('audio', { direction: 'recvonly' })
    self.pc.addTransceiver('video', { direction: 'recvonly' })

    const offer = await self.pc.createOffer()
    await self.pc.setLocalDescription(offer)
    const session = await new Promise(function (resolve, reject) {
      // @see https://github.com/rtcdn/rtcdn-draft
      const data = {
        api: baseUrl + '/rtc/v1/play/',
        tid: _getTid(),
        streamurl: url,
        clientip: null,
        sdp: offer.sdp
      }

      const xhr = new XMLHttpRequest()
      xhr.onload = function () {
        if (xhr.readyState !== xhr.DONE) return
        if (xhr.status !== 200) return reject(xhr)
        const data = JSON.parse(xhr.responseText)

        return data.code ? reject(xhr) : resolve(data)
      }
      xhr.open('POST', data.api, true)
      xhr.setRequestHeader('Content-type', 'application/json')
      xhr.send(JSON.stringify(data))
    })
    await self.pc.setRemoteDescription(
      new RTCSessionDescription({ type: 'answer', sdp: session.sdp })
    )
    // session.simulator = conf.schema + '//' + conf.urlObject.server + ':' + conf.port + '/rtc/v1/nack/'

    return session
  }

  // Close the player.
  self.close = function () {
    self.pc && self.pc.close()
    self.pc = null
  }
  self.ontrack = function (event) {
    self.stream.addTrack(event.track)
  }
  self.pc = new RTCPeerConnection(null)

  // Create a stream to add track to the stream, @see https://webrtc.org/getting-started/remote-streams
  self.stream = new MediaStream()

  // https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/ontrack
  self.pc.ontrack = function (event) {
    if (self.ontrack) {
      self.ontrack(event)
    }
  }

  return self
}
export function PIPCameraPlayer () {
  const self = {
  }

  // https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia
  self.constraints = {
    audio: true,
    video: {
      width: { ideal: 1920, max: 1920 }
    }
  }
  self.play = async function () {
    let stream2 = null
    try {
      stream2 = await navigator.mediaDevices.getUserMedia({
        audio: false,
        video: true
      })
    } catch (error) {
      console.info(error)
      throw error
    }
    stream2 && stream2.getTracks().forEach(function (track) {
      self.ontrack && self.ontrack({ track })
    })
  }
  self.ontrack = function (event) {
    // Add track to stream of SDK.
    self.stream.addTrack(event.track)
  }
  self.stream = new MediaStream()

  return self
}
