import Soap from '../utils/soap'

/**
 * @class
 * <p>
 * {@link https://www.onvif.org/specs/srv/media/ONVIF-Media2-Service-Spec-v1712.pdf}<br>
 * {@link https://www.onvif.org/ver20/media/wsdl/media.wsdl}<br>
 * </p>
 */
export default class Media2 {
  private readonly soap = new Soap()

  private timeDiff = 0

  private serviceAddress = null
  private username = null
  private password = null

  private readonly namespaceAttributes = [
    // 'xmlns:tns1="http://www.onvif.org/ver10/topics"',
    // 'xmlns:trt="http://www.onvif.org/ver10/media/wsdl"'
    // 'xmlns:trt="http://www.onvif.org/ver10/media/wsdl"',
    // 'xmlns:tt="http://www.onvif.org/ver10/schema"'
    'xmlns:tr2="http://www.onvif.org/ver20/media/wsdl"'
  ]

  /**
   * Call this function directly after instantiating a Media2 object.
   * @param timeDiff The onvif device's time difference.
   * @param serviceAddress An url object from url package - require('url').
   * @param username Optional only if the device does NOT have a user.
   * @param password Optional only if the device does NOT have a password.
   */
  init(timeDiff: number, serviceAddress: object, username: string | undefined, password: string | undefined) {
    this.timeDiff = timeDiff
    this.serviceAddress = serviceAddress
    this.username = username
    this.password = password
  }

  /**
   * Private function for creating a SOAP request.
   * @param body The body of the xml.
   */
  private createRequest(body: string) {
    return this.soap.createRequest({
      body: body,
      xmlns: this.namespaceAttributes,
      diff: this.timeDiff,
      username: this.username,
      password: this.password
    })
  }

  // ---------------------------------------------
  // Media2 API
  // ---------------------------------------------

  getProfiles() {
    // let soapBody = '<trt:GetProfiles/>'
    const soapBody = '<GetProfiles xmlns="http://www.onvif.org/ver10/media/wsdl"/>'
    const soapEnvelope = this.createRequest(soapBody)
    // console.log(soapEnvelope)
    return this.soap.makeRequest('media2', this.serviceAddress, 'GetProfiles', soapEnvelope)
  }

  getSnapshotUri(profileToken: string) {
    let soapBody = ''
    soapBody += '<trt:GetSnapshotUri>'
    soapBody += '<trt:ProfileToken>' + profileToken + '</trt:ProfileToken>'
    soapBody += '</trt:GetSnapshotUri>'
    const soapEnvelope = this.createRequest(soapBody)
    return this.soap.makeRequest('media2', this.serviceAddress, 'GetSnapshotUri', soapEnvelope)
  }
}
