import Camera from './camera'
import * as Util from './utils/util'

/**
 * If the OnvifManager class is used to connect to a camera, it will
 * manage your devices (cameras). It stores cameras by address. You
 * can use address to retrieve the camera.
 */

class OnvifManager {
  cameras: Record<string, Camera> = {}

  /**
   * Connects to an ONVIF device.
   * @param address The address of the ONVIF device (ie: 10.10.1.20)
   * @param port The port of the ONVIF device. Defaults to 80.
   * @param username The user name used to make a connection.
   * @param password The password used to make a connection.
   * @param servicePath The service path for the camera. If null or 'undefined' the default path according to the ONVIF spec will be used.
   */
  connect(address: string, port?: number, username?: string, password?: string, servicePath?: string) {
    const promise = new Promise<Camera>((resolve, reject) => {
      let errMsg = ''
      if ((errMsg = Util.isInvalidValue(address, 'string'))) {
        return reject(new Error('The "address" argument for connect is invalid: ' + errMsg))
      }

      const cacheKey = `${address}:${port}`
      const c = this.cameras[cacheKey]

      if (c) {
        return resolve(c)
      }

      // default to port 80 if none provided
      port = port || 80

      const camera = new Camera()

      return camera
        .connect(address, port, username, password, servicePath)
        .then(results => {
          // cache camera after successfully connecting
          this.cameras[cacheKey] = camera
          resolve(camera)
        })
        .catch(error => {
          console.error(error)
          reject(error)
        })
    })

    return promise
  }
}

export default new OnvifManager()
