/*
 * 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;
const moment = require('moment');

/**
 * List all the subscriptions under a specified topic.
 *
 * @param {string} resourceGroupName Name of the Resource group within the
 * Azure subscription.
 *
 * @param {string} namespaceName The namespace name
 *
 * @param {string} topicName The topic name.
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {number} [options.skip] Skip is only used if a previous operation
 * returned a partial result. If a previous response contains a nextLink
 * element, the value of the nextLink element will include a skip parameter
 * that specifies a starting point to use for subsequent calls.
 *
 * @param {number} [options.top] May be used to limit the number of results to
 * the most recent N usageDetails.
 *
 * @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 SBSubscriptionListResult} 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 _listByTopic(resourceGroupName, namespaceName, topicName, 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 skip = (options && options.skip !== undefined) ? options.skip : undefined;
  let top = (options && options.top !== undefined) ? options.top : undefined;
  // Validate
  try {
    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 (resourceGroupName !== null && resourceGroupName !== undefined) {
      if (resourceGroupName.length > 90)
      {
        throw new Error('"resourceGroupName" should satisfy the constraint - "MaxLength": 90');
      }
      if (resourceGroupName.length < 1)
      {
        throw new Error('"resourceGroupName" should satisfy the constraint - "MinLength": 1');
      }
    }
    if (namespaceName === null || namespaceName === undefined || typeof namespaceName.valueOf() !== 'string') {
      throw new Error('namespaceName cannot be null or undefined and it must be of type string.');
    }
    if (namespaceName !== null && namespaceName !== undefined) {
      if (namespaceName.length > 50)
      {
        throw new Error('"namespaceName" should satisfy the constraint - "MaxLength": 50');
      }
      if (namespaceName.length < 6)
      {
        throw new Error('"namespaceName" should satisfy the constraint - "MinLength": 6');
      }
    }
    if (topicName === null || topicName === undefined || typeof topicName.valueOf() !== 'string') {
      throw new Error('topicName cannot be null or undefined and it must be of type string.');
    }
    if (topicName !== null && topicName !== undefined) {
      if (topicName.length < 1)
      {
        throw new Error('"topicName" should satisfy the constraint - "MinLength": 1');
      }
    }
    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.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 (skip !== null && skip !== undefined && typeof skip !== 'number') {
      throw new Error('skip must be of type number.');
    }
    if (skip !== null && skip !== undefined) {
      if (skip > 1000)
      {
        throw new Error('"skip" should satisfy the constraint - "InclusiveMaximum": 1000');
      }
      if (skip < 0)
      {
        throw new Error('"skip" should satisfy the constraint - "InclusiveMinimum": 0');
      }
    }
    if (top !== null && top !== undefined && typeof top !== 'number') {
      throw new Error('top must be of type number.');
    }
    if (top !== null && top !== undefined) {
      if (top > 1000)
      {
        throw new Error('"top" should satisfy the constraint - "InclusiveMaximum": 1000');
      }
      if (top < 1)
      {
        throw new Error('"top" should satisfy the constraint - "InclusiveMinimum": 1');
      }
    }
    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.ServiceBus/namespaces/{namespaceName}/topics/{topicName}/subscriptions';
  requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
  requestUrl = requestUrl.replace('{namespaceName}', encodeURIComponent(namespaceName));
  requestUrl = requestUrl.replace('{topicName}', encodeURIComponent(topicName));
  requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
  let queryParameters = [];
  queryParameters.push('api-version=' + encodeURIComponent(this.client.apiVersion));
  if (skip !== null && skip !== undefined) {
    queryParameters.push('$skip=' + encodeURIComponent(skip.toString()));
  }
  if (top !== null && top !== undefined) {
    queryParameters.push('$top=' + encodeURIComponent(top.toString()));
  }
  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) {
          let internalError = null;
          if (parsedErrorResponse.error) internalError = parsedErrorResponse.error;
          error.code = internalError ? internalError.code : parsedErrorResponse.code;
          error.message = internalError ? internalError.message : parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          let resultMapper = new client.models['ErrorResponse']().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['SBSubscriptionListResult']().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);
  });
}

/**
 * Creates a topic subscription.
 *
 * @param {string} resourceGroupName Name of the Resource group within the
 * Azure subscription.
 *
 * @param {string} namespaceName The namespace name
 *
 * @param {string} topicName The topic name.
 *
 * @param {string} subscriptionName The subscription name.
 *
 * @param {object} parameters Parameters supplied to create a subscription
 * resource.
 *
 * @param {moment.duration} [parameters.lockDuration] ISO 8061 lock duration
 * timespan for the subscription. The default value is 1 minute.
 *
 * @param {boolean} [parameters.requiresSession] Value indicating if a
 * subscription supports the concept of sessions.
 *
 * @param {moment.duration} [parameters.defaultMessageTimeToLive] ISO 8061
 * Default message timespan to live value. This is the duration after which the
 * message expires, starting from when the message is sent to Service Bus. This
 * is the default value used when TimeToLive is not set on a message itself.
 *
 * @param {boolean} [parameters.deadLetteringOnFilterEvaluationExceptions]
 * Value that indicates whether a subscription has dead letter support on
 * filter evaluation exceptions.
 *
 * @param {boolean} [parameters.deadLetteringOnMessageExpiration] Value that
 * indicates whether a subscription has dead letter support when a message
 * expires.
 *
 * @param {moment.duration} [parameters.duplicateDetectionHistoryTimeWindow]
 * ISO 8601 timeSpan structure that defines the duration of the duplicate
 * detection history. The default value is 10 minutes.
 *
 * @param {number} [parameters.maxDeliveryCount] Number of maximum deliveries.
 *
 * @param {string} [parameters.status] Enumerates the possible values for the
 * status of a messaging entity. Possible values include: 'Active', 'Disabled',
 * 'Restoring', 'SendDisabled', 'ReceiveDisabled', 'Creating', 'Deleting',
 * 'Renaming', 'Unknown'
 *
 * @param {boolean} [parameters.enableBatchedOperations] Value that indicates
 * whether server-side batched operations are enabled.
 *
 * @param {moment.duration} [parameters.autoDeleteOnIdle] ISO 8061 timeSpan
 * idle interval after which the topic is automatically deleted. The minimum
 * duration is 5 minutes.
 *
 * @param {string} [parameters.forwardTo] Queue/Topic name to forward the
 * messages
 *
 * @param {string} [parameters.forwardDeadLetteredMessagesTo] Queue/Topic name
 * to forward the Dead Letter message
 *
 * @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 SBSubscription} 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 _createOrUpdate(resourceGroupName, namespaceName, topicName, subscriptionName, parameters, 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 (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 (resourceGroupName !== null && resourceGroupName !== undefined) {
      if (resourceGroupName.length > 90)
      {
        throw new Error('"resourceGroupName" should satisfy the constraint - "MaxLength": 90');
      }
      if (resourceGroupName.length < 1)
      {
        throw new Error('"resourceGroupName" should satisfy the constraint - "MinLength": 1');
      }
    }
    if (namespaceName === null || namespaceName === undefined || typeof namespaceName.valueOf() !== 'string') {
      throw new Error('namespaceName cannot be null or undefined and it must be of type string.');
    }
    if (namespaceName !== null && namespaceName !== undefined) {
      if (namespaceName.length > 50)
      {
        throw new Error('"namespaceName" should satisfy the constraint - "MaxLength": 50');
      }
      if (namespaceName.length < 6)
      {
        throw new Error('"namespaceName" should satisfy the constraint - "MinLength": 6');
      }
    }
    if (topicName === null || topicName === undefined || typeof topicName.valueOf() !== 'string') {
      throw new Error('topicName cannot be null or undefined and it must be of type string.');
    }
    if (topicName !== null && topicName !== undefined) {
      if (topicName.length < 1)
      {
        throw new Error('"topicName" should satisfy the constraint - "MinLength": 1');
      }
    }
    if (subscriptionName === null || subscriptionName === undefined || typeof subscriptionName.valueOf() !== 'string') {
      throw new Error('subscriptionName cannot be null or undefined and it must be of type string.');
    }
    if (subscriptionName !== null && subscriptionName !== undefined) {
      if (subscriptionName.length > 50)
      {
        throw new Error('"subscriptionName" should satisfy the constraint - "MaxLength": 50');
      }
      if (subscriptionName.length < 1)
      {
        throw new Error('"subscriptionName" should satisfy the constraint - "MinLength": 1');
      }
    }
    if (parameters === null || parameters === undefined) {
      throw new Error('parameters cannot be null or undefined.');
    }
    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.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 (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.ServiceBus/namespaces/{namespaceName}/topics/{topicName}/subscriptions/{subscriptionName}';
  requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
  requestUrl = requestUrl.replace('{namespaceName}', encodeURIComponent(namespaceName));
  requestUrl = requestUrl.replace('{topicName}', encodeURIComponent(topicName));
  requestUrl = requestUrl.replace('{subscriptionName}', encodeURIComponent(subscriptionName));
  requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
  let queryParameters = [];
  queryParameters.push('api-version=' + encodeURIComponent(this.client.apiVersion));
  if (queryParameters.length > 0) {
    requestUrl += '?' + queryParameters.join('&');
  }

  // Create HTTP transport objects
  let httpRequest = new WebResource();
  httpRequest.method = 'PUT';
  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['SBSubscription']().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) {
      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) {
          let internalError = null;
          if (parsedErrorResponse.error) internalError = parsedErrorResponse.error;
          error.code = internalError ? internalError.code : parsedErrorResponse.code;
          error.message = internalError ? internalError.message : parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          let resultMapper = new client.models['ErrorResponse']().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['SBSubscription']().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 a subscription from the specified topic.
 *
 * @param {string} resourceGroupName Name of the Resource group within the
 * Azure subscription.
 *
 * @param {string} namespaceName The namespace name
 *
 * @param {string} topicName The topic name.
 *
 * @param {string} subscriptionName The subscription 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(resourceGroupName, namespaceName, topicName, subscriptionName, 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 (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 (resourceGroupName !== null && resourceGroupName !== undefined) {
      if (resourceGroupName.length > 90)
      {
        throw new Error('"resourceGroupName" should satisfy the constraint - "MaxLength": 90');
      }
      if (resourceGroupName.length < 1)
      {
        throw new Error('"resourceGroupName" should satisfy the constraint - "MinLength": 1');
      }
    }
    if (namespaceName === null || namespaceName === undefined || typeof namespaceName.valueOf() !== 'string') {
      throw new Error('namespaceName cannot be null or undefined and it must be of type string.');
    }
    if (namespaceName !== null && namespaceName !== undefined) {
      if (namespaceName.length > 50)
      {
        throw new Error('"namespaceName" should satisfy the constraint - "MaxLength": 50');
      }
      if (namespaceName.length < 6)
      {
        throw new Error('"namespaceName" should satisfy the constraint - "MinLength": 6');
      }
    }
    if (topicName === null || topicName === undefined || typeof topicName.valueOf() !== 'string') {
      throw new Error('topicName cannot be null or undefined and it must be of type string.');
    }
    if (topicName !== null && topicName !== undefined) {
      if (topicName.length < 1)
      {
        throw new Error('"topicName" should satisfy the constraint - "MinLength": 1');
      }
    }
    if (subscriptionName === null || subscriptionName === undefined || typeof subscriptionName.valueOf() !== 'string') {
      throw new Error('subscriptionName cannot be null or undefined and it must be of type string.');
    }
    if (subscriptionName !== null && subscriptionName !== undefined) {
      if (subscriptionName.length > 50)
      {
        throw new Error('"subscriptionName" should satisfy the constraint - "MaxLength": 50');
      }
      if (subscriptionName.length < 1)
      {
        throw new Error('"subscriptionName" should satisfy the constraint - "MinLength": 1');
      }
    }
    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.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 (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.ServiceBus/namespaces/{namespaceName}/topics/{topicName}/subscriptions/{subscriptionName}';
  requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
  requestUrl = requestUrl.replace('{namespaceName}', encodeURIComponent(namespaceName));
  requestUrl = requestUrl.replace('{topicName}', encodeURIComponent(topicName));
  requestUrl = requestUrl.replace('{subscriptionName}', encodeURIComponent(subscriptionName));
  requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
  let queryParameters = [];
  queryParameters.push('api-version=' + encodeURIComponent(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 !== 200 && 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) {
          let internalError = null;
          if (parsedErrorResponse.error) internalError = parsedErrorResponse.error;
          error.code = internalError ? internalError.code : parsedErrorResponse.code;
          error.message = internalError ? internalError.message : parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          let resultMapper = new client.models['ErrorResponse']().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);
  });
}

/**
 * Returns a subscription description for the specified topic.
 *
 * @param {string} resourceGroupName Name of the Resource group within the
 * Azure subscription.
 *
 * @param {string} namespaceName The namespace name
 *
 * @param {string} topicName The topic name.
 *
 * @param {string} subscriptionName The subscription 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.
 *
 *                      {object} [result]   - The deserialized result object if an error did not occur.
 *                      See {@link SBSubscription} 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 _get(resourceGroupName, namespaceName, topicName, subscriptionName, 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 (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 (resourceGroupName !== null && resourceGroupName !== undefined) {
      if (resourceGroupName.length > 90)
      {
        throw new Error('"resourceGroupName" should satisfy the constraint - "MaxLength": 90');
      }
      if (resourceGroupName.length < 1)
      {
        throw new Error('"resourceGroupName" should satisfy the constraint - "MinLength": 1');
      }
    }
    if (namespaceName === null || namespaceName === undefined || typeof namespaceName.valueOf() !== 'string') {
      throw new Error('namespaceName cannot be null or undefined and it must be of type string.');
    }
    if (namespaceName !== null && namespaceName !== undefined) {
      if (namespaceName.length > 50)
      {
        throw new Error('"namespaceName" should satisfy the constraint - "MaxLength": 50');
      }
      if (namespaceName.length < 6)
      {
        throw new Error('"namespaceName" should satisfy the constraint - "MinLength": 6');
      }
    }
    if (topicName === null || topicName === undefined || typeof topicName.valueOf() !== 'string') {
      throw new Error('topicName cannot be null or undefined and it must be of type string.');
    }
    if (topicName !== null && topicName !== undefined) {
      if (topicName.length < 1)
      {
        throw new Error('"topicName" should satisfy the constraint - "MinLength": 1');
      }
    }
    if (subscriptionName === null || subscriptionName === undefined || typeof subscriptionName.valueOf() !== 'string') {
      throw new Error('subscriptionName cannot be null or undefined and it must be of type string.');
    }
    if (subscriptionName !== null && subscriptionName !== undefined) {
      if (subscriptionName.length > 50)
      {
        throw new Error('"subscriptionName" should satisfy the constraint - "MaxLength": 50');
      }
      if (subscriptionName.length < 1)
      {
        throw new Error('"subscriptionName" should satisfy the constraint - "MinLength": 1');
      }
    }
    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.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 (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.ServiceBus/namespaces/{namespaceName}/topics/{topicName}/subscriptions/{subscriptionName}';
  requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
  requestUrl = requestUrl.replace('{namespaceName}', encodeURIComponent(namespaceName));
  requestUrl = requestUrl.replace('{topicName}', encodeURIComponent(topicName));
  requestUrl = requestUrl.replace('{subscriptionName}', encodeURIComponent(subscriptionName));
  requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
  let queryParameters = [];
  queryParameters.push('api-version=' + encodeURIComponent(this.client.apiVersion));
  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) {
          let internalError = null;
          if (parsedErrorResponse.error) internalError = parsedErrorResponse.error;
          error.code = internalError ? internalError.code : parsedErrorResponse.code;
          error.message = internalError ? internalError.message : parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          let resultMapper = new client.models['ErrorResponse']().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['SBSubscription']().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);
  });
}

/**
 * List all the subscriptions under a specified topic.
 *
 * @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 SBSubscriptionListResult} 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 _listByTopicNext(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) {
          let internalError = null;
          if (parsedErrorResponse.error) internalError = parsedErrorResponse.error;
          error.code = internalError ? internalError.code : parsedErrorResponse.code;
          error.message = internalError ? internalError.message : parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          let resultMapper = new client.models['ErrorResponse']().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['SBSubscriptionListResult']().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 Subscriptions. */
class Subscriptions {
  /**
   * Create a Subscriptions.
   * @param {ServiceBusManagementClient} client Reference to the service client.
   */
  constructor(client) {
    this.client = client;
    this._listByTopic = _listByTopic;
    this._createOrUpdate = _createOrUpdate;
    this._deleteMethod = _deleteMethod;
    this._get = _get;
    this._listByTopicNext = _listByTopicNext;
  }

  /**
   * List all the subscriptions under a specified topic.
   *
   * @param {string} resourceGroupName Name of the Resource group within the
   * Azure subscription.
   *
   * @param {string} namespaceName The namespace name
   *
   * @param {string} topicName The topic name.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {number} [options.skip] Skip is only used if a previous operation
   * returned a partial result. If a previous response contains a nextLink
   * element, the value of the nextLink element will include a skip parameter
   * that specifies a starting point to use for subsequent calls.
   *
   * @param {number} [options.top] May be used to limit the number of results to
   * the most recent N usageDetails.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<SBSubscriptionListResult>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  listByTopicWithHttpOperationResponse(resourceGroupName, namespaceName, topicName, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._listByTopic(resourceGroupName, namespaceName, topicName, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * List all the subscriptions under a specified topic.
   *
   * @param {string} resourceGroupName Name of the Resource group within the
   * Azure subscription.
   *
   * @param {string} namespaceName The namespace name
   *
   * @param {string} topicName The topic name.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {number} [options.skip] Skip is only used if a previous operation
   * returned a partial result. If a previous response contains a nextLink
   * element, the value of the nextLink element will include a skip parameter
   * that specifies a starting point to use for subsequent calls.
   *
   * @param {number} [options.top] May be used to limit the number of results to
   * the most recent N usageDetails.
   *
   * @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 {SBSubscriptionListResult} - 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 SBSubscriptionListResult} 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.
   */
  listByTopic(resourceGroupName, namespaceName, topicName, 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._listByTopic(resourceGroupName, namespaceName, topicName, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._listByTopic(resourceGroupName, namespaceName, topicName, options, optionalCallback);
    }
  }

  /**
   * Creates a topic subscription.
   *
   * @param {string} resourceGroupName Name of the Resource group within the
   * Azure subscription.
   *
   * @param {string} namespaceName The namespace name
   *
   * @param {string} topicName The topic name.
   *
   * @param {string} subscriptionName The subscription name.
   *
   * @param {object} parameters Parameters supplied to create a subscription
   * resource.
   *
   * @param {moment.duration} [parameters.lockDuration] ISO 8061 lock duration
   * timespan for the subscription. The default value is 1 minute.
   *
   * @param {boolean} [parameters.requiresSession] Value indicating if a
   * subscription supports the concept of sessions.
   *
   * @param {moment.duration} [parameters.defaultMessageTimeToLive] ISO 8061
   * Default message timespan to live value. This is the duration after which the
   * message expires, starting from when the message is sent to Service Bus. This
   * is the default value used when TimeToLive is not set on a message itself.
   *
   * @param {boolean} [parameters.deadLetteringOnFilterEvaluationExceptions]
   * Value that indicates whether a subscription has dead letter support on
   * filter evaluation exceptions.
   *
   * @param {boolean} [parameters.deadLetteringOnMessageExpiration] Value that
   * indicates whether a subscription has dead letter support when a message
   * expires.
   *
   * @param {moment.duration} [parameters.duplicateDetectionHistoryTimeWindow]
   * ISO 8601 timeSpan structure that defines the duration of the duplicate
   * detection history. The default value is 10 minutes.
   *
   * @param {number} [parameters.maxDeliveryCount] Number of maximum deliveries.
   *
   * @param {string} [parameters.status] Enumerates the possible values for the
   * status of a messaging entity. Possible values include: 'Active', 'Disabled',
   * 'Restoring', 'SendDisabled', 'ReceiveDisabled', 'Creating', 'Deleting',
   * 'Renaming', 'Unknown'
   *
   * @param {boolean} [parameters.enableBatchedOperations] Value that indicates
   * whether server-side batched operations are enabled.
   *
   * @param {moment.duration} [parameters.autoDeleteOnIdle] ISO 8061 timeSpan
   * idle interval after which the topic is automatically deleted. The minimum
   * duration is 5 minutes.
   *
   * @param {string} [parameters.forwardTo] Queue/Topic name to forward the
   * messages
   *
   * @param {string} [parameters.forwardDeadLetteredMessagesTo] Queue/Topic name
   * to forward the Dead Letter message
   *
   * @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<SBSubscription>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  createOrUpdateWithHttpOperationResponse(resourceGroupName, namespaceName, topicName, subscriptionName, parameters, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._createOrUpdate(resourceGroupName, namespaceName, topicName, subscriptionName, parameters, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Creates a topic subscription.
   *
   * @param {string} resourceGroupName Name of the Resource group within the
   * Azure subscription.
   *
   * @param {string} namespaceName The namespace name
   *
   * @param {string} topicName The topic name.
   *
   * @param {string} subscriptionName The subscription name.
   *
   * @param {object} parameters Parameters supplied to create a subscription
   * resource.
   *
   * @param {moment.duration} [parameters.lockDuration] ISO 8061 lock duration
   * timespan for the subscription. The default value is 1 minute.
   *
   * @param {boolean} [parameters.requiresSession] Value indicating if a
   * subscription supports the concept of sessions.
   *
   * @param {moment.duration} [parameters.defaultMessageTimeToLive] ISO 8061
   * Default message timespan to live value. This is the duration after which the
   * message expires, starting from when the message is sent to Service Bus. This
   * is the default value used when TimeToLive is not set on a message itself.
   *
   * @param {boolean} [parameters.deadLetteringOnFilterEvaluationExceptions]
   * Value that indicates whether a subscription has dead letter support on
   * filter evaluation exceptions.
   *
   * @param {boolean} [parameters.deadLetteringOnMessageExpiration] Value that
   * indicates whether a subscription has dead letter support when a message
   * expires.
   *
   * @param {moment.duration} [parameters.duplicateDetectionHistoryTimeWindow]
   * ISO 8601 timeSpan structure that defines the duration of the duplicate
   * detection history. The default value is 10 minutes.
   *
   * @param {number} [parameters.maxDeliveryCount] Number of maximum deliveries.
   *
   * @param {string} [parameters.status] Enumerates the possible values for the
   * status of a messaging entity. Possible values include: 'Active', 'Disabled',
   * 'Restoring', 'SendDisabled', 'ReceiveDisabled', 'Creating', 'Deleting',
   * 'Renaming', 'Unknown'
   *
   * @param {boolean} [parameters.enableBatchedOperations] Value that indicates
   * whether server-side batched operations are enabled.
   *
   * @param {moment.duration} [parameters.autoDeleteOnIdle] ISO 8061 timeSpan
   * idle interval after which the topic is automatically deleted. The minimum
   * duration is 5 minutes.
   *
   * @param {string} [parameters.forwardTo] Queue/Topic name to forward the
   * messages
   *
   * @param {string} [parameters.forwardDeadLetteredMessagesTo] Queue/Topic name
   * to forward the Dead Letter message
   *
   * @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 {SBSubscription} - 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 SBSubscription} 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.
   */
  createOrUpdate(resourceGroupName, namespaceName, topicName, subscriptionName, parameters, 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._createOrUpdate(resourceGroupName, namespaceName, topicName, subscriptionName, parameters, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._createOrUpdate(resourceGroupName, namespaceName, topicName, subscriptionName, parameters, options, optionalCallback);
    }
  }

  /**
   * Deletes a subscription from the specified topic.
   *
   * @param {string} resourceGroupName Name of the Resource group within the
   * Azure subscription.
   *
   * @param {string} namespaceName The namespace name
   *
   * @param {string} topicName The topic name.
   *
   * @param {string} subscriptionName The subscription 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(resourceGroupName, namespaceName, topicName, subscriptionName, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._deleteMethod(resourceGroupName, namespaceName, topicName, subscriptionName, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Deletes a subscription from the specified topic.
   *
   * @param {string} resourceGroupName Name of the Resource group within the
   * Azure subscription.
   *
   * @param {string} namespaceName The namespace name
   *
   * @param {string} topicName The topic name.
   *
   * @param {string} subscriptionName The subscription 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(resourceGroupName, namespaceName, topicName, subscriptionName, 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(resourceGroupName, namespaceName, topicName, subscriptionName, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._deleteMethod(resourceGroupName, namespaceName, topicName, subscriptionName, options, optionalCallback);
    }
  }

  /**
   * Returns a subscription description for the specified topic.
   *
   * @param {string} resourceGroupName Name of the Resource group within the
   * Azure subscription.
   *
   * @param {string} namespaceName The namespace name
   *
   * @param {string} topicName The topic name.
   *
   * @param {string} subscriptionName The subscription 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<SBSubscription>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  getWithHttpOperationResponse(resourceGroupName, namespaceName, topicName, subscriptionName, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._get(resourceGroupName, namespaceName, topicName, subscriptionName, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Returns a subscription description for the specified topic.
   *
   * @param {string} resourceGroupName Name of the Resource group within the
   * Azure subscription.
   *
   * @param {string} namespaceName The namespace name
   *
   * @param {string} topicName The topic name.
   *
   * @param {string} subscriptionName The subscription 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 {SBSubscription} - 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 SBSubscription} 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.
   */
  get(resourceGroupName, namespaceName, topicName, subscriptionName, 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._get(resourceGroupName, namespaceName, topicName, subscriptionName, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._get(resourceGroupName, namespaceName, topicName, subscriptionName, options, optionalCallback);
    }
  }

  /**
   * List all the subscriptions under a specified topic.
   *
   * @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<SBSubscriptionListResult>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  listByTopicNextWithHttpOperationResponse(nextPageLink, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._listByTopicNext(nextPageLink, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * List all the subscriptions under a specified topic.
   *
   * @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 {SBSubscriptionListResult} - 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 SBSubscriptionListResult} 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.
   */
  listByTopicNext(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._listByTopicNext(nextPageLink, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._listByTopicNext(nextPageLink, options, optionalCallback);
    }
  }

}

module.exports = Subscriptions;
