/*
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for
 * license information.
 *
 * Code generated by Microsoft (R) AutoRest Code Generator.
 * Changes may cause incorrect behavior and will be lost if the code is
 * regenerated.
 */

'use strict';

const msRest = require('ms-rest');
const msRestAzure = require('ms-rest-azure');
const WebResource = msRest.WebResource;

/**
 * Retrieves all the backups in a device.
 *
 * @param {string} deviceName The device name
 *
 * @param {string} resourceGroupName The resource group name
 *
 * @param {string} managerName The manager name
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {string} [options.filter] OData Filter options
 *
 * @param {object} [options.customHeaders] Headers that will be added to the
 * request
 *
 * @param {function} callback - The callback.
 *
 * @returns {function} callback(err, result, request, response)
 *
 *                      {Error}  err        - The Error object if an error occurred, null otherwise.
 *
 *                      {object} [result]   - The deserialized result object if an error did not occur.
 *                      See {@link BackupList} for more information.
 *
 *                      {object} [request]  - The HTTP Request object if an error did not occur.
 *
 *                      {stream} [response] - The HTTP Response stream if an error did not occur.
 */
function _listByDevice(deviceName, resourceGroupName, managerName, options, callback) {
   /* jshint validthis: true */
  let client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }
  let filter = (options && options.filter !== undefined) ? options.filter : undefined;
  // Validate
  try {
    if (deviceName === null || deviceName === undefined || typeof deviceName.valueOf() !== 'string') {
      throw new Error('deviceName cannot be null or undefined and it must be of type string.');
    }
    if (this.client.subscriptionId === null || this.client.subscriptionId === undefined || typeof this.client.subscriptionId.valueOf() !== 'string') {
      throw new Error('this.client.subscriptionId cannot be null or undefined and it must be of type string.');
    }
    if (resourceGroupName === null || resourceGroupName === undefined || typeof resourceGroupName.valueOf() !== 'string') {
      throw new Error('resourceGroupName cannot be null or undefined and it must be of type string.');
    }
    if (managerName === null || managerName === undefined || typeof managerName.valueOf() !== 'string') {
      throw new Error('managerName cannot be null or undefined and it must be of type string.');
    }
    if (managerName !== null && managerName !== undefined) {
      if (managerName.length > 50)
      {
        throw new Error('"managerName" should satisfy the constraint - "MaxLength": 50');
      }
      if (managerName.length < 2)
      {
        throw new Error('"managerName" should satisfy the constraint - "MinLength": 2');
      }
    }
    if (this.client.apiVersion === null || this.client.apiVersion === undefined || typeof this.client.apiVersion.valueOf() !== 'string') {
      throw new Error('this.client.apiVersion cannot be null or undefined and it must be of type string.');
    }
    if (filter !== null && filter !== undefined && typeof filter.valueOf() !== 'string') {
      throw new Error('filter must be of type string.');
    }
    if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
      throw new Error('this.client.acceptLanguage must be of type string.');
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  let baseUrl = this.client.baseUri;
  let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}/backups';
  requestUrl = requestUrl.replace('{deviceName}', deviceName);
  requestUrl = requestUrl.replace('{subscriptionId}', this.client.subscriptionId);
  requestUrl = requestUrl.replace('{resourceGroupName}', resourceGroupName);
  requestUrl = requestUrl.replace('{managerName}', managerName);
  let queryParameters = [];
  queryParameters.push('api-version=' + this.client.apiVersion);
  if (filter !== null && filter !== undefined) {
    queryParameters.push('$filter=' + encodeURIComponent(filter));
  }
  if (queryParameters.length > 0) {
    requestUrl += '?' + queryParameters.join('&');
  }

  // Create HTTP transport objects
  let httpRequest = new WebResource();
  httpRequest.method = 'GET';
  httpRequest.url = requestUrl;
  httpRequest.headers = {};
  // Set Headers
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  if (this.client.generateClientRequestId) {
      httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if(options) {
    for(let headerName in options['customHeaders']) {
      if (options['customHeaders'].hasOwnProperty(headerName)) {
        httpRequest.headers[headerName] = options['customHeaders'][headerName];
      }
    }
  }
  httpRequest.body = null;
  // Send Request
  return client.pipeline(httpRequest, (err, response, responseBody) => {
    if (err) {
      return callback(err);
    }
    let statusCode = response.statusCode;
    if (statusCode !== 200) {
      let error = new Error(responseBody);
      error.statusCode = response.statusCode;
      error.request = msRest.stripRequest(httpRequest);
      error.response = msRest.stripResponse(response);
      if (responseBody === '') responseBody = null;
      let parsedErrorResponse;
      try {
        parsedErrorResponse = JSON.parse(responseBody);
        if (parsedErrorResponse) {
          if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
          if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
          if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          let resultMapper = new client.models['CloudError']().mapper();
          error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
        }
      } catch (defaultError) {
        error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
                         `- "${responseBody}" for the default response.`;
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    let result = null;
    if (responseBody === '') responseBody = null;
    // Deserialize Response
    if (statusCode === 200) {
      let parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          let resultMapper = new client.models['BackupList']().mapper();
          result = client.deserialize(resultMapper, parsedResponse, 'result');
        }
      } catch (error) {
        let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`);
        deserializationError.request = msRest.stripRequest(httpRequest);
        deserializationError.response = msRest.stripResponse(response);
        return callback(deserializationError);
      }
    }

    return callback(null, result, httpRequest, response);
  });
}


/**
 * Deletes the backup.
 *
 * @param {string} deviceName The device name
 *
 * @param {string} backupName The backup name.
 *
 * @param {string} resourceGroupName The resource group name
 *
 * @param {string} managerName The manager name
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {object} [options.customHeaders] Headers that will be added to the
 * request
 *
 * @param {function} callback - The callback.
 *
 * @returns {function} callback(err, result, request, response)
 *
 *                      {Error}  err        - The Error object if an error occurred, null otherwise.
 *
 *                      {null} [result]   - The deserialized result object if an error did not occur.
 *
 *                      {object} [request]  - The HTTP Request object if an error did not occur.
 *
 *                      {stream} [response] - The HTTP Response stream if an error did not occur.
 */
function _deleteMethod(deviceName, backupName, resourceGroupName, managerName, options, callback) {
   /* jshint validthis: true */
  let client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }

  if (!callback) {
    throw new Error('callback cannot be null.');
  }

  // Send request
  this.beginDeleteMethod(deviceName, backupName, resourceGroupName, managerName, options, (err, parsedResult, httpRequest, response) => {
    if (err) return callback(err);

    let initialResult = new msRest.HttpOperationResponse();
    initialResult.request = httpRequest;
    initialResult.response = response;
    initialResult.body = response.body;
    client.getLongRunningOperationResult(initialResult, options, (err, pollingResult) => {
      if (err) return callback(err);

      // Create Result
      let result = null;

      httpRequest = pollingResult.request;
      response = pollingResult.response;
      let responseBody = pollingResult.body;
      if (responseBody === '') responseBody = null;

      // Deserialize Response

      return callback(null, result, httpRequest, response);
    });
  });
}


/**
 * Clones the backup element as a new volume.
 *
 * @param {string} deviceName The device name
 *
 * @param {string} backupName The backup name.
 *
 * @param {string} backupElementName The backup element name.
 *
 * @param {object} parameters The clone request object.
 *
 * @param {string} parameters.targetDeviceId The path ID of the device which
 * will act as the clone target.
 *
 * @param {string} parameters.targetVolumeName The name of the new volume which
 * will be created and the backup will be cloned into.
 *
 * @param {array} parameters.targetAccessControlRecordIds The list of path IDs
 * of the access control records to be associated to the new cloned volume.
 *
 * @param {object} parameters.backupElement The backup element that is cloned.
 *
 * @param {string} parameters.backupElement.elementId The path ID that uniquely
 * identifies the backup element.
 *
 * @param {string} parameters.backupElement.elementName The name of the backup
 * element.
 *
 * @param {string} parameters.backupElement.elementType The hierarchical type
 * of the backup element.
 *
 * @param {number} parameters.backupElement.sizeInBytes The size in bytes.
 *
 * @param {string} parameters.backupElement.volumeName The name of the volume.
 *
 * @param {string} parameters.backupElement.volumeContainerId The path ID of
 * the volume container.
 *
 * @param {string} [parameters.backupElement.volumeType] The volume type.
 * Possible values include: 'Tiered', 'Archival', 'LocallyPinned'
 *
 * @param {string} resourceGroupName The resource group name
 *
 * @param {string} managerName The manager name
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {object} [options.customHeaders] Headers that will be added to the
 * request
 *
 * @param {function} callback - The callback.
 *
 * @returns {function} callback(err, result, request, response)
 *
 *                      {Error}  err        - The Error object if an error occurred, null otherwise.
 *
 *                      {null} [result]   - The deserialized result object if an error did not occur.
 *
 *                      {object} [request]  - The HTTP Request object if an error did not occur.
 *
 *                      {stream} [response] - The HTTP Response stream if an error did not occur.
 */
function _clone(deviceName, backupName, backupElementName, parameters, resourceGroupName, managerName, options, callback) {
   /* jshint validthis: true */
  let client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }

  if (!callback) {
    throw new Error('callback cannot be null.');
  }

  // Send request
  this.beginClone(deviceName, backupName, backupElementName, parameters, resourceGroupName, managerName, options, (err, parsedResult, httpRequest, response) => {
    if (err) return callback(err);

    let initialResult = new msRest.HttpOperationResponse();
    initialResult.request = httpRequest;
    initialResult.response = response;
    initialResult.body = response.body;
    client.getLongRunningOperationResult(initialResult, options, (err, pollingResult) => {
      if (err) return callback(err);

      // Create Result
      let result = null;

      httpRequest = pollingResult.request;
      response = pollingResult.response;
      let responseBody = pollingResult.body;
      if (responseBody === '') responseBody = null;

      // Deserialize Response

      return callback(null, result, httpRequest, response);
    });
  });
}


/**
 * Restores the backup on the device.
 *
 * @param {string} deviceName The device name
 *
 * @param {string} backupName The backupSet name
 *
 * @param {string} resourceGroupName The resource group name
 *
 * @param {string} managerName The manager name
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {object} [options.customHeaders] Headers that will be added to the
 * request
 *
 * @param {function} callback - The callback.
 *
 * @returns {function} callback(err, result, request, response)
 *
 *                      {Error}  err        - The Error object if an error occurred, null otherwise.
 *
 *                      {null} [result]   - The deserialized result object if an error did not occur.
 *
 *                      {object} [request]  - The HTTP Request object if an error did not occur.
 *
 *                      {stream} [response] - The HTTP Response stream if an error did not occur.
 */
function _restore(deviceName, backupName, resourceGroupName, managerName, options, callback) {
   /* jshint validthis: true */
  let client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }

  if (!callback) {
    throw new Error('callback cannot be null.');
  }

  // Send request
  this.beginRestore(deviceName, backupName, resourceGroupName, managerName, options, (err, parsedResult, httpRequest, response) => {
    if (err) return callback(err);

    let initialResult = new msRest.HttpOperationResponse();
    initialResult.request = httpRequest;
    initialResult.response = response;
    initialResult.body = response.body;
    client.getLongRunningOperationResult(initialResult, options, (err, pollingResult) => {
      if (err) return callback(err);

      // Create Result
      let result = null;

      httpRequest = pollingResult.request;
      response = pollingResult.response;
      let responseBody = pollingResult.body;
      if (responseBody === '') responseBody = null;

      // Deserialize Response

      return callback(null, result, httpRequest, response);
    });
  });
}

/**
 * Deletes the backup.
 *
 * @param {string} deviceName The device name
 *
 * @param {string} backupName The backup name.
 *
 * @param {string} resourceGroupName The resource group name
 *
 * @param {string} managerName The manager name
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {object} [options.customHeaders] Headers that will be added to the
 * request
 *
 * @param {function} callback - The callback.
 *
 * @returns {function} callback(err, result, request, response)
 *
 *                      {Error}  err        - The Error object if an error occurred, null otherwise.
 *
 *                      {null} [result]   - The deserialized result object if an error did not occur.
 *
 *                      {object} [request]  - The HTTP Request object if an error did not occur.
 *
 *                      {stream} [response] - The HTTP Response stream if an error did not occur.
 */
function _beginDeleteMethod(deviceName, backupName, resourceGroupName, managerName, options, callback) {
   /* jshint validthis: true */
  let client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }
  // Validate
  try {
    if (deviceName === null || deviceName === undefined || typeof deviceName.valueOf() !== 'string') {
      throw new Error('deviceName cannot be null or undefined and it must be of type string.');
    }
    if (backupName === null || backupName === undefined || typeof backupName.valueOf() !== 'string') {
      throw new Error('backupName cannot be null or undefined and it must be of type string.');
    }
    if (this.client.subscriptionId === null || this.client.subscriptionId === undefined || typeof this.client.subscriptionId.valueOf() !== 'string') {
      throw new Error('this.client.subscriptionId cannot be null or undefined and it must be of type string.');
    }
    if (resourceGroupName === null || resourceGroupName === undefined || typeof resourceGroupName.valueOf() !== 'string') {
      throw new Error('resourceGroupName cannot be null or undefined and it must be of type string.');
    }
    if (managerName === null || managerName === undefined || typeof managerName.valueOf() !== 'string') {
      throw new Error('managerName cannot be null or undefined and it must be of type string.');
    }
    if (managerName !== null && managerName !== undefined) {
      if (managerName.length > 50)
      {
        throw new Error('"managerName" should satisfy the constraint - "MaxLength": 50');
      }
      if (managerName.length < 2)
      {
        throw new Error('"managerName" should satisfy the constraint - "MinLength": 2');
      }
    }
    if (this.client.apiVersion === null || this.client.apiVersion === undefined || typeof this.client.apiVersion.valueOf() !== 'string') {
      throw new Error('this.client.apiVersion cannot be null or undefined and it must be of type string.');
    }
    if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
      throw new Error('this.client.acceptLanguage must be of type string.');
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  let baseUrl = this.client.baseUri;
  let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}/backups/{backupName}';
  requestUrl = requestUrl.replace('{deviceName}', deviceName);
  requestUrl = requestUrl.replace('{backupName}', backupName);
  requestUrl = requestUrl.replace('{subscriptionId}', this.client.subscriptionId);
  requestUrl = requestUrl.replace('{resourceGroupName}', resourceGroupName);
  requestUrl = requestUrl.replace('{managerName}', managerName);
  let queryParameters = [];
  queryParameters.push('api-version=' + this.client.apiVersion);
  if (queryParameters.length > 0) {
    requestUrl += '?' + queryParameters.join('&');
  }

  // Create HTTP transport objects
  let httpRequest = new WebResource();
  httpRequest.method = 'DELETE';
  httpRequest.url = requestUrl;
  httpRequest.headers = {};
  // Set Headers
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  if (this.client.generateClientRequestId) {
      httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if(options) {
    for(let headerName in options['customHeaders']) {
      if (options['customHeaders'].hasOwnProperty(headerName)) {
        httpRequest.headers[headerName] = options['customHeaders'][headerName];
      }
    }
  }
  httpRequest.body = null;
  // Send Request
  return client.pipeline(httpRequest, (err, response, responseBody) => {
    if (err) {
      return callback(err);
    }
    let statusCode = response.statusCode;
    if (statusCode !== 202 && statusCode !== 204) {
      let error = new Error(responseBody);
      error.statusCode = response.statusCode;
      error.request = msRest.stripRequest(httpRequest);
      error.response = msRest.stripResponse(response);
      if (responseBody === '') responseBody = null;
      let parsedErrorResponse;
      try {
        parsedErrorResponse = JSON.parse(responseBody);
        if (parsedErrorResponse) {
          if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
          if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
          if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          let resultMapper = new client.models['CloudError']().mapper();
          error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
        }
      } catch (defaultError) {
        error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
                         `- "${responseBody}" for the default response.`;
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    let result = null;
    if (responseBody === '') responseBody = null;

    return callback(null, result, httpRequest, response);
  });
}

/**
 * Clones the backup element as a new volume.
 *
 * @param {string} deviceName The device name
 *
 * @param {string} backupName The backup name.
 *
 * @param {string} backupElementName The backup element name.
 *
 * @param {object} parameters The clone request object.
 *
 * @param {string} parameters.targetDeviceId The path ID of the device which
 * will act as the clone target.
 *
 * @param {string} parameters.targetVolumeName The name of the new volume which
 * will be created and the backup will be cloned into.
 *
 * @param {array} parameters.targetAccessControlRecordIds The list of path IDs
 * of the access control records to be associated to the new cloned volume.
 *
 * @param {object} parameters.backupElement The backup element that is cloned.
 *
 * @param {string} parameters.backupElement.elementId The path ID that uniquely
 * identifies the backup element.
 *
 * @param {string} parameters.backupElement.elementName The name of the backup
 * element.
 *
 * @param {string} parameters.backupElement.elementType The hierarchical type
 * of the backup element.
 *
 * @param {number} parameters.backupElement.sizeInBytes The size in bytes.
 *
 * @param {string} parameters.backupElement.volumeName The name of the volume.
 *
 * @param {string} parameters.backupElement.volumeContainerId The path ID of
 * the volume container.
 *
 * @param {string} [parameters.backupElement.volumeType] The volume type.
 * Possible values include: 'Tiered', 'Archival', 'LocallyPinned'
 *
 * @param {string} resourceGroupName The resource group name
 *
 * @param {string} managerName The manager name
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {object} [options.customHeaders] Headers that will be added to the
 * request
 *
 * @param {function} callback - The callback.
 *
 * @returns {function} callback(err, result, request, response)
 *
 *                      {Error}  err        - The Error object if an error occurred, null otherwise.
 *
 *                      {null} [result]   - The deserialized result object if an error did not occur.
 *
 *                      {object} [request]  - The HTTP Request object if an error did not occur.
 *
 *                      {stream} [response] - The HTTP Response stream if an error did not occur.
 */
function _beginClone(deviceName, backupName, backupElementName, parameters, resourceGroupName, managerName, options, callback) {
   /* jshint validthis: true */
  let client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }
  // Validate
  try {
    if (deviceName === null || deviceName === undefined || typeof deviceName.valueOf() !== 'string') {
      throw new Error('deviceName cannot be null or undefined and it must be of type string.');
    }
    if (backupName === null || backupName === undefined || typeof backupName.valueOf() !== 'string') {
      throw new Error('backupName cannot be null or undefined and it must be of type string.');
    }
    if (backupElementName === null || backupElementName === undefined || typeof backupElementName.valueOf() !== 'string') {
      throw new Error('backupElementName cannot be null or undefined and it must be of type string.');
    }
    if (parameters === null || parameters === undefined) {
      throw new Error('parameters cannot be null or undefined.');
    }
    if (this.client.subscriptionId === null || this.client.subscriptionId === undefined || typeof this.client.subscriptionId.valueOf() !== 'string') {
      throw new Error('this.client.subscriptionId cannot be null or undefined and it must be of type string.');
    }
    if (resourceGroupName === null || resourceGroupName === undefined || typeof resourceGroupName.valueOf() !== 'string') {
      throw new Error('resourceGroupName cannot be null or undefined and it must be of type string.');
    }
    if (managerName === null || managerName === undefined || typeof managerName.valueOf() !== 'string') {
      throw new Error('managerName cannot be null or undefined and it must be of type string.');
    }
    if (managerName !== null && managerName !== undefined) {
      if (managerName.length > 50)
      {
        throw new Error('"managerName" should satisfy the constraint - "MaxLength": 50');
      }
      if (managerName.length < 2)
      {
        throw new Error('"managerName" should satisfy the constraint - "MinLength": 2');
      }
    }
    if (this.client.apiVersion === null || this.client.apiVersion === undefined || typeof this.client.apiVersion.valueOf() !== 'string') {
      throw new Error('this.client.apiVersion cannot be null or undefined and it must be of type string.');
    }
    if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
      throw new Error('this.client.acceptLanguage must be of type string.');
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  let baseUrl = this.client.baseUri;
  let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}/backups/{backupName}/elements/{backupElementName}/clone';
  requestUrl = requestUrl.replace('{deviceName}', deviceName);
  requestUrl = requestUrl.replace('{backupName}', backupName);
  requestUrl = requestUrl.replace('{backupElementName}', backupElementName);
  requestUrl = requestUrl.replace('{subscriptionId}', this.client.subscriptionId);
  requestUrl = requestUrl.replace('{resourceGroupName}', resourceGroupName);
  requestUrl = requestUrl.replace('{managerName}', managerName);
  let queryParameters = [];
  queryParameters.push('api-version=' + this.client.apiVersion);
  if (queryParameters.length > 0) {
    requestUrl += '?' + queryParameters.join('&');
  }

  // Create HTTP transport objects
  let httpRequest = new WebResource();
  httpRequest.method = 'POST';
  httpRequest.url = requestUrl;
  httpRequest.headers = {};
  // Set Headers
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  if (this.client.generateClientRequestId) {
      httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if(options) {
    for(let headerName in options['customHeaders']) {
      if (options['customHeaders'].hasOwnProperty(headerName)) {
        httpRequest.headers[headerName] = options['customHeaders'][headerName];
      }
    }
  }
  // Serialize Request
  let requestContent = null;
  let requestModel = null;
  try {
    if (parameters !== null && parameters !== undefined) {
      let requestModelMapper = new client.models['CloneRequest']().mapper();
      requestModel = client.serialize(requestModelMapper, parameters, 'parameters');
      requestContent = JSON.stringify(requestModel);
    }
  } catch (error) {
    let serializationError = new Error(`Error "${error.message}" occurred in serializing the ` +
        `payload - ${JSON.stringify(parameters, null, 2)}.`);
    return callback(serializationError);
  }
  httpRequest.body = requestContent;
  // Send Request
  return client.pipeline(httpRequest, (err, response, responseBody) => {
    if (err) {
      return callback(err);
    }
    let statusCode = response.statusCode;
    if (statusCode !== 200 && statusCode !== 202) {
      let error = new Error(responseBody);
      error.statusCode = response.statusCode;
      error.request = msRest.stripRequest(httpRequest);
      error.response = msRest.stripResponse(response);
      if (responseBody === '') responseBody = null;
      let parsedErrorResponse;
      try {
        parsedErrorResponse = JSON.parse(responseBody);
        if (parsedErrorResponse) {
          if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
          if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
          if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          let resultMapper = new client.models['CloudError']().mapper();
          error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
        }
      } catch (defaultError) {
        error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
                         `- "${responseBody}" for the default response.`;
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    let result = null;
    if (responseBody === '') responseBody = null;

    return callback(null, result, httpRequest, response);
  });
}

/**
 * Restores the backup on the device.
 *
 * @param {string} deviceName The device name
 *
 * @param {string} backupName The backupSet name
 *
 * @param {string} resourceGroupName The resource group name
 *
 * @param {string} managerName The manager name
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {object} [options.customHeaders] Headers that will be added to the
 * request
 *
 * @param {function} callback - The callback.
 *
 * @returns {function} callback(err, result, request, response)
 *
 *                      {Error}  err        - The Error object if an error occurred, null otherwise.
 *
 *                      {null} [result]   - The deserialized result object if an error did not occur.
 *
 *                      {object} [request]  - The HTTP Request object if an error did not occur.
 *
 *                      {stream} [response] - The HTTP Response stream if an error did not occur.
 */
function _beginRestore(deviceName, backupName, resourceGroupName, managerName, options, callback) {
   /* jshint validthis: true */
  let client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }
  // Validate
  try {
    if (deviceName === null || deviceName === undefined || typeof deviceName.valueOf() !== 'string') {
      throw new Error('deviceName cannot be null or undefined and it must be of type string.');
    }
    if (backupName === null || backupName === undefined || typeof backupName.valueOf() !== 'string') {
      throw new Error('backupName cannot be null or undefined and it must be of type string.');
    }
    if (this.client.subscriptionId === null || this.client.subscriptionId === undefined || typeof this.client.subscriptionId.valueOf() !== 'string') {
      throw new Error('this.client.subscriptionId cannot be null or undefined and it must be of type string.');
    }
    if (resourceGroupName === null || resourceGroupName === undefined || typeof resourceGroupName.valueOf() !== 'string') {
      throw new Error('resourceGroupName cannot be null or undefined and it must be of type string.');
    }
    if (managerName === null || managerName === undefined || typeof managerName.valueOf() !== 'string') {
      throw new Error('managerName cannot be null or undefined and it must be of type string.');
    }
    if (managerName !== null && managerName !== undefined) {
      if (managerName.length > 50)
      {
        throw new Error('"managerName" should satisfy the constraint - "MaxLength": 50');
      }
      if (managerName.length < 2)
      {
        throw new Error('"managerName" should satisfy the constraint - "MinLength": 2');
      }
    }
    if (this.client.apiVersion === null || this.client.apiVersion === undefined || typeof this.client.apiVersion.valueOf() !== 'string') {
      throw new Error('this.client.apiVersion cannot be null or undefined and it must be of type string.');
    }
    if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
      throw new Error('this.client.acceptLanguage must be of type string.');
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  let baseUrl = this.client.baseUri;
  let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}/backups/{backupName}/restore';
  requestUrl = requestUrl.replace('{deviceName}', deviceName);
  requestUrl = requestUrl.replace('{backupName}', backupName);
  requestUrl = requestUrl.replace('{subscriptionId}', this.client.subscriptionId);
  requestUrl = requestUrl.replace('{resourceGroupName}', resourceGroupName);
  requestUrl = requestUrl.replace('{managerName}', managerName);
  let queryParameters = [];
  queryParameters.push('api-version=' + this.client.apiVersion);
  if (queryParameters.length > 0) {
    requestUrl += '?' + queryParameters.join('&');
  }

  // Create HTTP transport objects
  let httpRequest = new WebResource();
  httpRequest.method = 'POST';
  httpRequest.url = requestUrl;
  httpRequest.headers = {};
  // Set Headers
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  if (this.client.generateClientRequestId) {
      httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if(options) {
    for(let headerName in options['customHeaders']) {
      if (options['customHeaders'].hasOwnProperty(headerName)) {
        httpRequest.headers[headerName] = options['customHeaders'][headerName];
      }
    }
  }
  httpRequest.body = null;
  // Send Request
  return client.pipeline(httpRequest, (err, response, responseBody) => {
    if (err) {
      return callback(err);
    }
    let statusCode = response.statusCode;
    if (statusCode !== 200 && statusCode !== 202) {
      let error = new Error(responseBody);
      error.statusCode = response.statusCode;
      error.request = msRest.stripRequest(httpRequest);
      error.response = msRest.stripResponse(response);
      if (responseBody === '') responseBody = null;
      let parsedErrorResponse;
      try {
        parsedErrorResponse = JSON.parse(responseBody);
        if (parsedErrorResponse) {
          if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
          if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
          if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          let resultMapper = new client.models['CloudError']().mapper();
          error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
        }
      } catch (defaultError) {
        error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
                         `- "${responseBody}" for the default response.`;
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    let result = null;
    if (responseBody === '') responseBody = null;

    return callback(null, result, httpRequest, response);
  });
}

/**
 * Retrieves all the backups in a device.
 *
 * @param {string} nextPageLink The NextLink from the previous successful call
 * to List operation.
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {object} [options.customHeaders] Headers that will be added to the
 * request
 *
 * @param {function} callback - The callback.
 *
 * @returns {function} callback(err, result, request, response)
 *
 *                      {Error}  err        - The Error object if an error occurred, null otherwise.
 *
 *                      {object} [result]   - The deserialized result object if an error did not occur.
 *                      See {@link BackupList} for more information.
 *
 *                      {object} [request]  - The HTTP Request object if an error did not occur.
 *
 *                      {stream} [response] - The HTTP Response stream if an error did not occur.
 */
function _listByDeviceNext(nextPageLink, options, callback) {
   /* jshint validthis: true */
  let client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }
  // Validate
  try {
    if (nextPageLink === null || nextPageLink === undefined || typeof nextPageLink.valueOf() !== 'string') {
      throw new Error('nextPageLink cannot be null or undefined and it must be of type string.');
    }
    if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
      throw new Error('this.client.acceptLanguage must be of type string.');
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  let requestUrl = '{nextLink}';
  requestUrl = requestUrl.replace('{nextLink}', nextPageLink);

  // Create HTTP transport objects
  let httpRequest = new WebResource();
  httpRequest.method = 'GET';
  httpRequest.url = requestUrl;
  httpRequest.headers = {};
  // Set Headers
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  if (this.client.generateClientRequestId) {
      httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if(options) {
    for(let headerName in options['customHeaders']) {
      if (options['customHeaders'].hasOwnProperty(headerName)) {
        httpRequest.headers[headerName] = options['customHeaders'][headerName];
      }
    }
  }
  httpRequest.body = null;
  // Send Request
  return client.pipeline(httpRequest, (err, response, responseBody) => {
    if (err) {
      return callback(err);
    }
    let statusCode = response.statusCode;
    if (statusCode !== 200) {
      let error = new Error(responseBody);
      error.statusCode = response.statusCode;
      error.request = msRest.stripRequest(httpRequest);
      error.response = msRest.stripResponse(response);
      if (responseBody === '') responseBody = null;
      let parsedErrorResponse;
      try {
        parsedErrorResponse = JSON.parse(responseBody);
        if (parsedErrorResponse) {
          if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
          if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
          if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          let resultMapper = new client.models['CloudError']().mapper();
          error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
        }
      } catch (defaultError) {
        error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
                         `- "${responseBody}" for the default response.`;
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    let result = null;
    if (responseBody === '') responseBody = null;
    // Deserialize Response
    if (statusCode === 200) {
      let parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          let resultMapper = new client.models['BackupList']().mapper();
          result = client.deserialize(resultMapper, parsedResponse, 'result');
        }
      } catch (error) {
        let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`);
        deserializationError.request = msRest.stripRequest(httpRequest);
        deserializationError.response = msRest.stripResponse(response);
        return callback(deserializationError);
      }
    }

    return callback(null, result, httpRequest, response);
  });
}

/** Class representing a Backups. */
class Backups {
  /**
   * Create a Backups.
   * @param {StorSimple8000SeriesManagementClient} client Reference to the service client.
   */
  constructor(client) {
    this.client = client;
    this._listByDevice = _listByDevice;
    this._deleteMethod = _deleteMethod;
    this._clone = _clone;
    this._restore = _restore;
    this._beginDeleteMethod = _beginDeleteMethod;
    this._beginClone = _beginClone;
    this._beginRestore = _beginRestore;
    this._listByDeviceNext = _listByDeviceNext;
  }

  /**
   * Retrieves all the backups in a device.
   *
   * @param {string} deviceName The device name
   *
   * @param {string} resourceGroupName The resource group name
   *
   * @param {string} managerName The manager name
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {string} [options.filter] OData Filter options
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<BackupList>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  listByDeviceWithHttpOperationResponse(deviceName, resourceGroupName, managerName, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._listByDevice(deviceName, resourceGroupName, managerName, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Retrieves all the backups in a device.
   *
   * @param {string} deviceName The device name
   *
   * @param {string} resourceGroupName The resource group name
   *
   * @param {string} managerName The manager name
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {string} [options.filter] OData Filter options
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @param {function} [optionalCallback] - The optional callback.
   *
   * @returns {function|Promise} If a callback was passed as the last parameter
   * then it returns the callback else returns a Promise.
   *
   * {Promise} A promise is returned
   *
   *                      @resolve {BackupList} - The deserialized result object.
   *
   *                      @reject {Error} - The error object.
   *
   * {function} optionalCallback(err, result, request, response)
   *
   *                      {Error}  err        - The Error object if an error occurred, null otherwise.
   *
   *                      {object} [result]   - The deserialized result object if an error did not occur.
   *                      See {@link BackupList} for more information.
   *
   *                      {object} [request]  - The HTTP Request object if an error did not occur.
   *
   *                      {stream} [response] - The HTTP Response stream if an error did not occur.
   */
  listByDevice(deviceName, resourceGroupName, managerName, options, optionalCallback) {
    let client = this.client;
    let self = this;
    if (!optionalCallback && typeof options === 'function') {
      optionalCallback = options;
      options = null;
    }
    if (!optionalCallback) {
      return new Promise((resolve, reject) => {
        self._listByDevice(deviceName, resourceGroupName, managerName, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._listByDevice(deviceName, resourceGroupName, managerName, options, optionalCallback);
    }
  }

  /**
   * Deletes the backup.
   *
   * @param {string} deviceName The device name
   *
   * @param {string} backupName The backup name.
   *
   * @param {string} resourceGroupName The resource group name
   *
   * @param {string} managerName The manager name
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<null>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  deleteMethodWithHttpOperationResponse(deviceName, backupName, resourceGroupName, managerName, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._deleteMethod(deviceName, backupName, resourceGroupName, managerName, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Deletes the backup.
   *
   * @param {string} deviceName The device name
   *
   * @param {string} backupName The backup name.
   *
   * @param {string} resourceGroupName The resource group name
   *
   * @param {string} managerName The manager name
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @param {function} [optionalCallback] - The optional callback.
   *
   * @returns {function|Promise} If a callback was passed as the last parameter
   * then it returns the callback else returns a Promise.
   *
   * {Promise} A promise is returned
   *
   *                      @resolve {null} - The deserialized result object.
   *
   *                      @reject {Error} - The error object.
   *
   * {function} optionalCallback(err, result, request, response)
   *
   *                      {Error}  err        - The Error object if an error occurred, null otherwise.
   *
   *                      {null} [result]   - The deserialized result object if an error did not occur.
   *
   *                      {object} [request]  - The HTTP Request object if an error did not occur.
   *
   *                      {stream} [response] - The HTTP Response stream if an error did not occur.
   */
  deleteMethod(deviceName, backupName, resourceGroupName, managerName, options, optionalCallback) {
    let client = this.client;
    let self = this;
    if (!optionalCallback && typeof options === 'function') {
      optionalCallback = options;
      options = null;
    }
    if (!optionalCallback) {
      return new Promise((resolve, reject) => {
        self._deleteMethod(deviceName, backupName, resourceGroupName, managerName, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._deleteMethod(deviceName, backupName, resourceGroupName, managerName, options, optionalCallback);
    }
  }

  /**
   * Clones the backup element as a new volume.
   *
   * @param {string} deviceName The device name
   *
   * @param {string} backupName The backup name.
   *
   * @param {string} backupElementName The backup element name.
   *
   * @param {object} parameters The clone request object.
   *
   * @param {string} parameters.targetDeviceId The path ID of the device which
   * will act as the clone target.
   *
   * @param {string} parameters.targetVolumeName The name of the new volume which
   * will be created and the backup will be cloned into.
   *
   * @param {array} parameters.targetAccessControlRecordIds The list of path IDs
   * of the access control records to be associated to the new cloned volume.
   *
   * @param {object} parameters.backupElement The backup element that is cloned.
   *
   * @param {string} parameters.backupElement.elementId The path ID that uniquely
   * identifies the backup element.
   *
   * @param {string} parameters.backupElement.elementName The name of the backup
   * element.
   *
   * @param {string} parameters.backupElement.elementType The hierarchical type
   * of the backup element.
   *
   * @param {number} parameters.backupElement.sizeInBytes The size in bytes.
   *
   * @param {string} parameters.backupElement.volumeName The name of the volume.
   *
   * @param {string} parameters.backupElement.volumeContainerId The path ID of
   * the volume container.
   *
   * @param {string} [parameters.backupElement.volumeType] The volume type.
   * Possible values include: 'Tiered', 'Archival', 'LocallyPinned'
   *
   * @param {string} resourceGroupName The resource group name
   *
   * @param {string} managerName The manager name
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<null>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  cloneWithHttpOperationResponse(deviceName, backupName, backupElementName, parameters, resourceGroupName, managerName, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._clone(deviceName, backupName, backupElementName, parameters, resourceGroupName, managerName, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Clones the backup element as a new volume.
   *
   * @param {string} deviceName The device name
   *
   * @param {string} backupName The backup name.
   *
   * @param {string} backupElementName The backup element name.
   *
   * @param {object} parameters The clone request object.
   *
   * @param {string} parameters.targetDeviceId The path ID of the device which
   * will act as the clone target.
   *
   * @param {string} parameters.targetVolumeName The name of the new volume which
   * will be created and the backup will be cloned into.
   *
   * @param {array} parameters.targetAccessControlRecordIds The list of path IDs
   * of the access control records to be associated to the new cloned volume.
   *
   * @param {object} parameters.backupElement The backup element that is cloned.
   *
   * @param {string} parameters.backupElement.elementId The path ID that uniquely
   * identifies the backup element.
   *
   * @param {string} parameters.backupElement.elementName The name of the backup
   * element.
   *
   * @param {string} parameters.backupElement.elementType The hierarchical type
   * of the backup element.
   *
   * @param {number} parameters.backupElement.sizeInBytes The size in bytes.
   *
   * @param {string} parameters.backupElement.volumeName The name of the volume.
   *
   * @param {string} parameters.backupElement.volumeContainerId The path ID of
   * the volume container.
   *
   * @param {string} [parameters.backupElement.volumeType] The volume type.
   * Possible values include: 'Tiered', 'Archival', 'LocallyPinned'
   *
   * @param {string} resourceGroupName The resource group name
   *
   * @param {string} managerName The manager name
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @param {function} [optionalCallback] - The optional callback.
   *
   * @returns {function|Promise} If a callback was passed as the last parameter
   * then it returns the callback else returns a Promise.
   *
   * {Promise} A promise is returned
   *
   *                      @resolve {null} - The deserialized result object.
   *
   *                      @reject {Error} - The error object.
   *
   * {function} optionalCallback(err, result, request, response)
   *
   *                      {Error}  err        - The Error object if an error occurred, null otherwise.
   *
   *                      {null} [result]   - The deserialized result object if an error did not occur.
   *
   *                      {object} [request]  - The HTTP Request object if an error did not occur.
   *
   *                      {stream} [response] - The HTTP Response stream if an error did not occur.
   */
  clone(deviceName, backupName, backupElementName, parameters, resourceGroupName, managerName, options, optionalCallback) {
    let client = this.client;
    let self = this;
    if (!optionalCallback && typeof options === 'function') {
      optionalCallback = options;
      options = null;
    }
    if (!optionalCallback) {
      return new Promise((resolve, reject) => {
        self._clone(deviceName, backupName, backupElementName, parameters, resourceGroupName, managerName, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._clone(deviceName, backupName, backupElementName, parameters, resourceGroupName, managerName, options, optionalCallback);
    }
  }

  /**
   * Restores the backup on the device.
   *
   * @param {string} deviceName The device name
   *
   * @param {string} backupName The backupSet name
   *
   * @param {string} resourceGroupName The resource group name
   *
   * @param {string} managerName The manager name
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<null>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  restoreWithHttpOperationResponse(deviceName, backupName, resourceGroupName, managerName, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._restore(deviceName, backupName, resourceGroupName, managerName, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Restores the backup on the device.
   *
   * @param {string} deviceName The device name
   *
   * @param {string} backupName The backupSet name
   *
   * @param {string} resourceGroupName The resource group name
   *
   * @param {string} managerName The manager name
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @param {function} [optionalCallback] - The optional callback.
   *
   * @returns {function|Promise} If a callback was passed as the last parameter
   * then it returns the callback else returns a Promise.
   *
   * {Promise} A promise is returned
   *
   *                      @resolve {null} - The deserialized result object.
   *
   *                      @reject {Error} - The error object.
   *
   * {function} optionalCallback(err, result, request, response)
   *
   *                      {Error}  err        - The Error object if an error occurred, null otherwise.
   *
   *                      {null} [result]   - The deserialized result object if an error did not occur.
   *
   *                      {object} [request]  - The HTTP Request object if an error did not occur.
   *
   *                      {stream} [response] - The HTTP Response stream if an error did not occur.
   */
  restore(deviceName, backupName, resourceGroupName, managerName, options, optionalCallback) {
    let client = this.client;
    let self = this;
    if (!optionalCallback && typeof options === 'function') {
      optionalCallback = options;
      options = null;
    }
    if (!optionalCallback) {
      return new Promise((resolve, reject) => {
        self._restore(deviceName, backupName, resourceGroupName, managerName, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._restore(deviceName, backupName, resourceGroupName, managerName, options, optionalCallback);
    }
  }

  /**
   * Deletes the backup.
   *
   * @param {string} deviceName The device name
   *
   * @param {string} backupName The backup name.
   *
   * @param {string} resourceGroupName The resource group name
   *
   * @param {string} managerName The manager name
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<null>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  beginDeleteMethodWithHttpOperationResponse(deviceName, backupName, resourceGroupName, managerName, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._beginDeleteMethod(deviceName, backupName, resourceGroupName, managerName, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Deletes the backup.
   *
   * @param {string} deviceName The device name
   *
   * @param {string} backupName The backup name.
   *
   * @param {string} resourceGroupName The resource group name
   *
   * @param {string} managerName The manager name
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @param {function} [optionalCallback] - The optional callback.
   *
   * @returns {function|Promise} If a callback was passed as the last parameter
   * then it returns the callback else returns a Promise.
   *
   * {Promise} A promise is returned
   *
   *                      @resolve {null} - The deserialized result object.
   *
   *                      @reject {Error} - The error object.
   *
   * {function} optionalCallback(err, result, request, response)
   *
   *                      {Error}  err        - The Error object if an error occurred, null otherwise.
   *
   *                      {null} [result]   - The deserialized result object if an error did not occur.
   *
   *                      {object} [request]  - The HTTP Request object if an error did not occur.
   *
   *                      {stream} [response] - The HTTP Response stream if an error did not occur.
   */
  beginDeleteMethod(deviceName, backupName, resourceGroupName, managerName, options, optionalCallback) {
    let client = this.client;
    let self = this;
    if (!optionalCallback && typeof options === 'function') {
      optionalCallback = options;
      options = null;
    }
    if (!optionalCallback) {
      return new Promise((resolve, reject) => {
        self._beginDeleteMethod(deviceName, backupName, resourceGroupName, managerName, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._beginDeleteMethod(deviceName, backupName, resourceGroupName, managerName, options, optionalCallback);
    }
  }

  /**
   * Clones the backup element as a new volume.
   *
   * @param {string} deviceName The device name
   *
   * @param {string} backupName The backup name.
   *
   * @param {string} backupElementName The backup element name.
   *
   * @param {object} parameters The clone request object.
   *
   * @param {string} parameters.targetDeviceId The path ID of the device which
   * will act as the clone target.
   *
   * @param {string} parameters.targetVolumeName The name of the new volume which
   * will be created and the backup will be cloned into.
   *
   * @param {array} parameters.targetAccessControlRecordIds The list of path IDs
   * of the access control records to be associated to the new cloned volume.
   *
   * @param {object} parameters.backupElement The backup element that is cloned.
   *
   * @param {string} parameters.backupElement.elementId The path ID that uniquely
   * identifies the backup element.
   *
   * @param {string} parameters.backupElement.elementName The name of the backup
   * element.
   *
   * @param {string} parameters.backupElement.elementType The hierarchical type
   * of the backup element.
   *
   * @param {number} parameters.backupElement.sizeInBytes The size in bytes.
   *
   * @param {string} parameters.backupElement.volumeName The name of the volume.
   *
   * @param {string} parameters.backupElement.volumeContainerId The path ID of
   * the volume container.
   *
   * @param {string} [parameters.backupElement.volumeType] The volume type.
   * Possible values include: 'Tiered', 'Archival', 'LocallyPinned'
   *
   * @param {string} resourceGroupName The resource group name
   *
   * @param {string} managerName The manager name
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<null>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  beginCloneWithHttpOperationResponse(deviceName, backupName, backupElementName, parameters, resourceGroupName, managerName, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._beginClone(deviceName, backupName, backupElementName, parameters, resourceGroupName, managerName, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Clones the backup element as a new volume.
   *
   * @param {string} deviceName The device name
   *
   * @param {string} backupName The backup name.
   *
   * @param {string} backupElementName The backup element name.
   *
   * @param {object} parameters The clone request object.
   *
   * @param {string} parameters.targetDeviceId The path ID of the device which
   * will act as the clone target.
   *
   * @param {string} parameters.targetVolumeName The name of the new volume which
   * will be created and the backup will be cloned into.
   *
   * @param {array} parameters.targetAccessControlRecordIds The list of path IDs
   * of the access control records to be associated to the new cloned volume.
   *
   * @param {object} parameters.backupElement The backup element that is cloned.
   *
   * @param {string} parameters.backupElement.elementId The path ID that uniquely
   * identifies the backup element.
   *
   * @param {string} parameters.backupElement.elementName The name of the backup
   * element.
   *
   * @param {string} parameters.backupElement.elementType The hierarchical type
   * of the backup element.
   *
   * @param {number} parameters.backupElement.sizeInBytes The size in bytes.
   *
   * @param {string} parameters.backupElement.volumeName The name of the volume.
   *
   * @param {string} parameters.backupElement.volumeContainerId The path ID of
   * the volume container.
   *
   * @param {string} [parameters.backupElement.volumeType] The volume type.
   * Possible values include: 'Tiered', 'Archival', 'LocallyPinned'
   *
   * @param {string} resourceGroupName The resource group name
   *
   * @param {string} managerName The manager name
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @param {function} [optionalCallback] - The optional callback.
   *
   * @returns {function|Promise} If a callback was passed as the last parameter
   * then it returns the callback else returns a Promise.
   *
   * {Promise} A promise is returned
   *
   *                      @resolve {null} - The deserialized result object.
   *
   *                      @reject {Error} - The error object.
   *
   * {function} optionalCallback(err, result, request, response)
   *
   *                      {Error}  err        - The Error object if an error occurred, null otherwise.
   *
   *                      {null} [result]   - The deserialized result object if an error did not occur.
   *
   *                      {object} [request]  - The HTTP Request object if an error did not occur.
   *
   *                      {stream} [response] - The HTTP Response stream if an error did not occur.
   */
  beginClone(deviceName, backupName, backupElementName, parameters, resourceGroupName, managerName, options, optionalCallback) {
    let client = this.client;
    let self = this;
    if (!optionalCallback && typeof options === 'function') {
      optionalCallback = options;
      options = null;
    }
    if (!optionalCallback) {
      return new Promise((resolve, reject) => {
        self._beginClone(deviceName, backupName, backupElementName, parameters, resourceGroupName, managerName, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._beginClone(deviceName, backupName, backupElementName, parameters, resourceGroupName, managerName, options, optionalCallback);
    }
  }

  /**
   * Restores the backup on the device.
   *
   * @param {string} deviceName The device name
   *
   * @param {string} backupName The backupSet name
   *
   * @param {string} resourceGroupName The resource group name
   *
   * @param {string} managerName The manager name
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<null>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  beginRestoreWithHttpOperationResponse(deviceName, backupName, resourceGroupName, managerName, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._beginRestore(deviceName, backupName, resourceGroupName, managerName, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Restores the backup on the device.
   *
   * @param {string} deviceName The device name
   *
   * @param {string} backupName The backupSet name
   *
   * @param {string} resourceGroupName The resource group name
   *
   * @param {string} managerName The manager name
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @param {function} [optionalCallback] - The optional callback.
   *
   * @returns {function|Promise} If a callback was passed as the last parameter
   * then it returns the callback else returns a Promise.
   *
   * {Promise} A promise is returned
   *
   *                      @resolve {null} - The deserialized result object.
   *
   *                      @reject {Error} - The error object.
   *
   * {function} optionalCallback(err, result, request, response)
   *
   *                      {Error}  err        - The Error object if an error occurred, null otherwise.
   *
   *                      {null} [result]   - The deserialized result object if an error did not occur.
   *
   *                      {object} [request]  - The HTTP Request object if an error did not occur.
   *
   *                      {stream} [response] - The HTTP Response stream if an error did not occur.
   */
  beginRestore(deviceName, backupName, resourceGroupName, managerName, options, optionalCallback) {
    let client = this.client;
    let self = this;
    if (!optionalCallback && typeof options === 'function') {
      optionalCallback = options;
      options = null;
    }
    if (!optionalCallback) {
      return new Promise((resolve, reject) => {
        self._beginRestore(deviceName, backupName, resourceGroupName, managerName, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._beginRestore(deviceName, backupName, resourceGroupName, managerName, options, optionalCallback);
    }
  }

  /**
   * Retrieves all the backups in a device.
   *
   * @param {string} nextPageLink The NextLink from the previous successful call
   * to List operation.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<BackupList>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  listByDeviceNextWithHttpOperationResponse(nextPageLink, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._listByDeviceNext(nextPageLink, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Retrieves all the backups in a device.
   *
   * @param {string} nextPageLink The NextLink from the previous successful call
   * to List operation.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @param {function} [optionalCallback] - The optional callback.
   *
   * @returns {function|Promise} If a callback was passed as the last parameter
   * then it returns the callback else returns a Promise.
   *
   * {Promise} A promise is returned
   *
   *                      @resolve {BackupList} - The deserialized result object.
   *
   *                      @reject {Error} - The error object.
   *
   * {function} optionalCallback(err, result, request, response)
   *
   *                      {Error}  err        - The Error object if an error occurred, null otherwise.
   *
   *                      {object} [result]   - The deserialized result object if an error did not occur.
   *                      See {@link BackupList} for more information.
   *
   *                      {object} [request]  - The HTTP Request object if an error did not occur.
   *
   *                      {stream} [response] - The HTTP Response stream if an error did not occur.
   */
  listByDeviceNext(nextPageLink, options, optionalCallback) {
    let client = this.client;
    let self = this;
    if (!optionalCallback && typeof options === 'function') {
      optionalCallback = options;
      options = null;
    }
    if (!optionalCallback) {
      return new Promise((resolve, reject) => {
        self._listByDeviceNext(nextPageLink, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._listByDeviceNext(nextPageLink, options, optionalCallback);
    }
  }

}

module.exports = Backups;
