/*
 * 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;

/**
 * Lists all subscriptions of the API Management service instance.
 *
 * @param {string} resourceGroupName The name of the resource group.
 *
 * @param {string} serviceName The name of the API Management service.
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {string} [options.filter] |   Field     |     Usage     |
 * Supported operators     |     Supported functions
 * |</br>|-------------|-------------|-------------|-------------|</br>| name |
 * filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
 * endswith | </br>| displayName | filter | ge, le, eq, ne, gt, lt |
 * substringof, contains, startswith, endswith | </br>| stateComment | filter |
 * ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |
 * </br>| ownerId | filter | ge, le, eq, ne, gt, lt | substringof, contains,
 * startswith, endswith | </br>| scope | filter | ge, le, eq, ne, gt, lt |
 * substringof, contains, startswith, endswith | </br>| userId | filter | ge,
 * le, eq, ne, gt, lt | substringof, contains, startswith, endswith | </br>|
 * productId | filter | ge, le, eq, ne, gt, lt | substringof, contains,
 * startswith, endswith | </br>| state | filter | eq |     | </br>| user |
 * expand |     |     | </br>
 *
 * @param {number} [options.top] Number of records to return.
 *
 * @param {number} [options.skip] Number of records to skip.
 *
 * @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 SubscriptionCollection} 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 _list(resourceGroupName, serviceName, 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;
  let top = (options && options.top !== undefined) ? options.top : undefined;
  let skip = (options && options.skip !== undefined) ? options.skip : 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 (serviceName === null || serviceName === undefined || typeof serviceName.valueOf() !== 'string') {
      throw new Error('serviceName cannot be null or undefined and it must be of type string.');
    }
    if (serviceName !== null && serviceName !== undefined) {
      if (serviceName.length > 50)
      {
        throw new Error('"serviceName" should satisfy the constraint - "MaxLength": 50');
      }
      if (serviceName.length < 1)
      {
        throw new Error('"serviceName" should satisfy the constraint - "MinLength": 1');
      }
      if (serviceName.match(/^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/) === null)
      {
        throw new Error('"serviceName" should satisfy the constraint - "Pattern": /^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/');
      }
    }
    if (filter !== null && filter !== undefined && typeof filter.valueOf() !== 'string') {
      throw new Error('filter must be of type string.');
    }
    if (top !== null && top !== undefined && typeof top !== 'number') {
      throw new Error('top must be of type number.');
    }
    if (top !== null && top !== undefined) {
      if (top < 1)
      {
        throw new Error('"top" should satisfy the constraint - "InclusiveMinimum": 1');
      }
    }
    if (skip !== null && skip !== undefined && typeof skip !== 'number') {
      throw new Error('skip must be of type number.');
    }
    if (skip !== null && skip !== undefined) {
      if (skip < 0)
      {
        throw new Error('"skip" should satisfy the constraint - "InclusiveMinimum": 0');
      }
    }
    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.ApiManagement/service/{serviceName}/subscriptions';
  requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
  requestUrl = requestUrl.replace('{serviceName}', encodeURIComponent(serviceName));
  requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
  let queryParameters = [];
  if (filter !== null && filter !== undefined) {
    queryParameters.push('$filter=' + encodeURIComponent(filter));
  }
  if (top !== null && top !== undefined) {
    queryParameters.push('$top=' + encodeURIComponent(top.toString()));
  }
  if (skip !== null && skip !== undefined) {
    queryParameters.push('$skip=' + encodeURIComponent(skip.toString()));
  }
  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['SubscriptionCollection']().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);
  });
}

/**
 * Gets the entity state (Etag) version of the apimanagement subscription
 * specified by its identifier.
 *
 * @param {string} resourceGroupName The name of the resource group.
 *
 * @param {string} serviceName The name of the API Management service.
 *
 * @param {string} sid Subscription entity Identifier. The entity represents
 * the association between a user and a product in API Management.
 *
 * @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 _getEntityTag(resourceGroupName, serviceName, sid, 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 (serviceName === null || serviceName === undefined || typeof serviceName.valueOf() !== 'string') {
      throw new Error('serviceName cannot be null or undefined and it must be of type string.');
    }
    if (serviceName !== null && serviceName !== undefined) {
      if (serviceName.length > 50)
      {
        throw new Error('"serviceName" should satisfy the constraint - "MaxLength": 50');
      }
      if (serviceName.length < 1)
      {
        throw new Error('"serviceName" should satisfy the constraint - "MinLength": 1');
      }
      if (serviceName.match(/^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/) === null)
      {
        throw new Error('"serviceName" should satisfy the constraint - "Pattern": /^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/');
      }
    }
    if (sid === null || sid === undefined || typeof sid.valueOf() !== 'string') {
      throw new Error('sid cannot be null or undefined and it must be of type string.');
    }
    if (sid !== null && sid !== undefined) {
      if (sid.length > 256)
      {
        throw new Error('"sid" should satisfy the constraint - "MaxLength": 256');
      }
      if (sid.match(/^[^*#&+:<>?]+$/) === null)
      {
        throw new Error('"sid" should satisfy the constraint - "Pattern": /^[^*#&+:<>?]+$/');
      }
    }
    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.ApiManagement/service/{serviceName}/subscriptions/{sid}';
  requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
  requestUrl = requestUrl.replace('{serviceName}', encodeURIComponent(serviceName));
  requestUrl = requestUrl.replace('{sid}', encodeURIComponent(sid));
  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 = 'HEAD';
  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;

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

/**
 * Gets the specified Subscription entity.
 *
 * @param {string} resourceGroupName The name of the resource group.
 *
 * @param {string} serviceName The name of the API Management service.
 *
 * @param {string} sid Subscription entity Identifier. The entity represents
 * the association between a user and a product in API Management.
 *
 * @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 SubscriptionContract} 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, serviceName, sid, 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 (serviceName === null || serviceName === undefined || typeof serviceName.valueOf() !== 'string') {
      throw new Error('serviceName cannot be null or undefined and it must be of type string.');
    }
    if (serviceName !== null && serviceName !== undefined) {
      if (serviceName.length > 50)
      {
        throw new Error('"serviceName" should satisfy the constraint - "MaxLength": 50');
      }
      if (serviceName.length < 1)
      {
        throw new Error('"serviceName" should satisfy the constraint - "MinLength": 1');
      }
      if (serviceName.match(/^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/) === null)
      {
        throw new Error('"serviceName" should satisfy the constraint - "Pattern": /^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/');
      }
    }
    if (sid === null || sid === undefined || typeof sid.valueOf() !== 'string') {
      throw new Error('sid cannot be null or undefined and it must be of type string.');
    }
    if (sid !== null && sid !== undefined) {
      if (sid.length > 256)
      {
        throw new Error('"sid" should satisfy the constraint - "MaxLength": 256');
      }
      if (sid.match(/^[^*#&+:<>?]+$/) === null)
      {
        throw new Error('"sid" should satisfy the constraint - "Pattern": /^[^*#&+:<>?]+$/');
      }
    }
    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.ApiManagement/service/{serviceName}/subscriptions/{sid}';
  requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
  requestUrl = requestUrl.replace('{serviceName}', encodeURIComponent(serviceName));
  requestUrl = requestUrl.replace('{sid}', encodeURIComponent(sid));
  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['SubscriptionContract']().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 or updates the subscription of specified user to the specified
 * product.
 *
 * @param {string} resourceGroupName The name of the resource group.
 *
 * @param {string} serviceName The name of the API Management service.
 *
 * @param {string} sid Subscription entity Identifier. The entity represents
 * the association between a user and a product in API Management.
 *
 * @param {object} parameters Create parameters.
 *
 * @param {string} [parameters.ownerId] User (user id path) for whom
 * subscription is being created in form /users/{userId}
 *
 * @param {string} parameters.scope Scope like /products/{productId} or /apis
 * or /apis/{apiId}.
 *
 * @param {string} parameters.displayName Subscription name.
 *
 * @param {string} [parameters.primaryKey] Primary subscription key. If not
 * specified during request key will be generated automatically.
 *
 * @param {string} [parameters.secondaryKey] Secondary subscription key. If not
 * specified during request key will be generated automatically.
 *
 * @param {string} [parameters.state] Initial subscription state. If no value
 * is specified, subscription is created with Submitted state. Possible states
 * are * active – the subscription is active, * suspended – the subscription is
 * blocked, and the subscriber cannot call any APIs of the product, * submitted
 * – the subscription request has been made by the developer, but has not yet
 * been approved or rejected, * rejected – the subscription request has been
 * denied by an administrator, * cancelled – the subscription has been
 * cancelled by the developer or administrator, * expired – the subscription
 * reached its expiration date and was deactivated. Possible values include:
 * 'suspended', 'active', 'expired', 'submitted', 'rejected', 'cancelled'
 *
 * @param {boolean} [parameters.allowTracing] Determines whether tracing can be
 * enabled
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {boolean} [options.notify] Notify change in Subscription State.
 * - If false, do not send any email notification for change of state of
 * subscription
 * - If true, send email notification of change of state of subscription
 *
 * @param {string} [options.ifMatch] ETag of the Entity. Not required when
 * creating an entity, but required when updating an entity.
 *
 * @param {string} [options.appType] Determines the type of application which
 * send the create user request. Default is legacy publisher portal. Possible
 * values include: 'portal', 'developerPortal'
 *
 * @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 SubscriptionContract} 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, serviceName, sid, 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.');
  }
  let notify = (options && options.notify !== undefined) ? options.notify : undefined;
  let ifMatch = (options && options.ifMatch !== undefined) ? options.ifMatch : undefined;
  let appType = (options && options.appType !== undefined) ? options.appType : 'portal';
  // 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 (serviceName === null || serviceName === undefined || typeof serviceName.valueOf() !== 'string') {
      throw new Error('serviceName cannot be null or undefined and it must be of type string.');
    }
    if (serviceName !== null && serviceName !== undefined) {
      if (serviceName.length > 50)
      {
        throw new Error('"serviceName" should satisfy the constraint - "MaxLength": 50');
      }
      if (serviceName.length < 1)
      {
        throw new Error('"serviceName" should satisfy the constraint - "MinLength": 1');
      }
      if (serviceName.match(/^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/) === null)
      {
        throw new Error('"serviceName" should satisfy the constraint - "Pattern": /^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/');
      }
    }
    if (sid === null || sid === undefined || typeof sid.valueOf() !== 'string') {
      throw new Error('sid cannot be null or undefined and it must be of type string.');
    }
    if (sid !== null && sid !== undefined) {
      if (sid.length > 256)
      {
        throw new Error('"sid" should satisfy the constraint - "MaxLength": 256');
      }
      if (sid.match(/^[^*#&+:<>?]+$/) === null)
      {
        throw new Error('"sid" should satisfy the constraint - "Pattern": /^[^*#&+:<>?]+$/');
      }
    }
    if (parameters === null || parameters === undefined) {
      throw new Error('parameters cannot be null or undefined.');
    }
    if (notify !== null && notify !== undefined && typeof notify !== 'boolean') {
      throw new Error('notify must be of type boolean.');
    }
    if (ifMatch !== null && ifMatch !== undefined && typeof ifMatch.valueOf() !== 'string') {
      throw new Error('ifMatch must be of type string.');
    }
    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 (appType !== null && appType !== undefined && typeof appType.valueOf() !== 'string') {
      throw new Error('appType 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.ApiManagement/service/{serviceName}/subscriptions/{sid}';
  requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
  requestUrl = requestUrl.replace('{serviceName}', encodeURIComponent(serviceName));
  requestUrl = requestUrl.replace('{sid}', encodeURIComponent(sid));
  requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
  let queryParameters = [];
  if (notify !== null && notify !== undefined) {
    queryParameters.push('notify=' + encodeURIComponent(notify.toString()));
  }
  queryParameters.push('api-version=' + encodeURIComponent(this.client.apiVersion));
  if (appType !== null && appType !== undefined) {
    queryParameters.push('appType=' + encodeURIComponent(appType));
  }
  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 (ifMatch !== undefined && ifMatch !== null) {
    httpRequest.headers['If-Match'] = ifMatch;
  }
  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['SubscriptionCreateParameters']().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 !== 201) {
      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['SubscriptionContract']().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);
      }
    }
    // Deserialize Response
    if (statusCode === 201) {
      let parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          let resultMapper = new client.models['SubscriptionContract']().mapper();
          result = client.deserialize(resultMapper, parsedResponse, 'result');
        }
      } catch (error) {
        let deserializationError1 = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`);
        deserializationError1.request = msRest.stripRequest(httpRequest);
        deserializationError1.response = msRest.stripResponse(response);
        return callback(deserializationError1);
      }
    }

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

/**
 * Updates the details of a subscription specified by its identifier.
 *
 * @param {string} resourceGroupName The name of the resource group.
 *
 * @param {string} serviceName The name of the API Management service.
 *
 * @param {string} sid Subscription entity Identifier. The entity represents
 * the association between a user and a product in API Management.
 *
 * @param {object} parameters Update parameters.
 *
 * @param {string} [parameters.ownerId] User identifier path: /users/{userId}
 *
 * @param {string} [parameters.scope] Scope like /products/{productId} or /apis
 * or /apis/{apiId}
 *
 * @param {date} [parameters.expirationDate] Subscription expiration date. The
 * setting is for audit purposes only and the subscription is not automatically
 * expired. The subscription lifecycle can be managed by using the `state`
 * property. The date conforms to the following format: `yyyy-MM-ddTHH:mm:ssZ`
 * as specified by the ISO 8601 standard.
 *
 * @param {string} [parameters.displayName] Subscription name.
 *
 * @param {string} [parameters.primaryKey] Primary subscription key.
 *
 * @param {string} [parameters.secondaryKey] Secondary subscription key.
 *
 * @param {string} [parameters.state] Subscription state. Possible states are *
 * active – the subscription is active, * suspended – the subscription is
 * blocked, and the subscriber cannot call any APIs of the product, * submitted
 * – the subscription request has been made by the developer, but has not yet
 * been approved or rejected, * rejected – the subscription request has been
 * denied by an administrator, * cancelled – the subscription has been
 * cancelled by the developer or administrator, * expired – the subscription
 * reached its expiration date and was deactivated. Possible values include:
 * 'suspended', 'active', 'expired', 'submitted', 'rejected', 'cancelled'
 *
 * @param {string} [parameters.stateComment] Comments describing subscription
 * state change by the administrator when the state is changed to the
 * 'rejected'.
 *
 * @param {boolean} [parameters.allowTracing] Determines whether tracing can be
 * enabled
 *
 * @param {string} ifMatch ETag of the Entity. ETag should match the current
 * entity state from the header response of the GET request or it should be *
 * for unconditional update.
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {boolean} [options.notify] Notify change in Subscription State.
 * - If false, do not send any email notification for change of state of
 * subscription
 * - If true, send email notification of change of state of subscription
 *
 * @param {string} [options.appType] Determines the type of application which
 * send the create user request. Default is legacy publisher portal. Possible
 * values include: 'portal', 'developerPortal'
 *
 * @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 _update(resourceGroupName, serviceName, sid, parameters, ifMatch, 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 notify = (options && options.notify !== undefined) ? options.notify : undefined;
  let appType = (options && options.appType !== undefined) ? options.appType : 'portal';
  // 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 (serviceName === null || serviceName === undefined || typeof serviceName.valueOf() !== 'string') {
      throw new Error('serviceName cannot be null or undefined and it must be of type string.');
    }
    if (serviceName !== null && serviceName !== undefined) {
      if (serviceName.length > 50)
      {
        throw new Error('"serviceName" should satisfy the constraint - "MaxLength": 50');
      }
      if (serviceName.length < 1)
      {
        throw new Error('"serviceName" should satisfy the constraint - "MinLength": 1');
      }
      if (serviceName.match(/^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/) === null)
      {
        throw new Error('"serviceName" should satisfy the constraint - "Pattern": /^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/');
      }
    }
    if (sid === null || sid === undefined || typeof sid.valueOf() !== 'string') {
      throw new Error('sid cannot be null or undefined and it must be of type string.');
    }
    if (sid !== null && sid !== undefined) {
      if (sid.length > 256)
      {
        throw new Error('"sid" should satisfy the constraint - "MaxLength": 256');
      }
      if (sid.match(/^[^*#&+:<>?]+$/) === null)
      {
        throw new Error('"sid" should satisfy the constraint - "Pattern": /^[^*#&+:<>?]+$/');
      }
    }
    if (parameters === null || parameters === undefined) {
      throw new Error('parameters cannot be null or undefined.');
    }
    if (notify !== null && notify !== undefined && typeof notify !== 'boolean') {
      throw new Error('notify must be of type boolean.');
    }
    if (ifMatch === null || ifMatch === undefined || typeof ifMatch.valueOf() !== 'string') {
      throw new Error('ifMatch cannot be null or undefined and it must be of type string.');
    }
    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 (appType !== null && appType !== undefined && typeof appType.valueOf() !== 'string') {
      throw new Error('appType 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.ApiManagement/service/{serviceName}/subscriptions/{sid}';
  requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
  requestUrl = requestUrl.replace('{serviceName}', encodeURIComponent(serviceName));
  requestUrl = requestUrl.replace('{sid}', encodeURIComponent(sid));
  requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
  let queryParameters = [];
  if (notify !== null && notify !== undefined) {
    queryParameters.push('notify=' + encodeURIComponent(notify.toString()));
  }
  queryParameters.push('api-version=' + encodeURIComponent(this.client.apiVersion));
  if (appType !== null && appType !== undefined) {
    queryParameters.push('appType=' + encodeURIComponent(appType));
  }
  if (queryParameters.length > 0) {
    requestUrl += '?' + queryParameters.join('&');
  }

  // Create HTTP transport objects
  let httpRequest = new WebResource();
  httpRequest.method = 'PATCH';
  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 (ifMatch !== undefined && ifMatch !== null) {
    httpRequest.headers['If-Match'] = ifMatch;
  }
  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['SubscriptionUpdateParameters']().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 !== 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);
  });
}

/**
 * Deletes the specified subscription.
 *
 * @param {string} resourceGroupName The name of the resource group.
 *
 * @param {string} serviceName The name of the API Management service.
 *
 * @param {string} sid Subscription entity Identifier. The entity represents
 * the association between a user and a product in API Management.
 *
 * @param {string} ifMatch ETag of the Entity. ETag should match the current
 * entity state from the header response of the GET request or it should be *
 * for unconditional update.
 *
 * @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, serviceName, sid, ifMatch, 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 (serviceName === null || serviceName === undefined || typeof serviceName.valueOf() !== 'string') {
      throw new Error('serviceName cannot be null or undefined and it must be of type string.');
    }
    if (serviceName !== null && serviceName !== undefined) {
      if (serviceName.length > 50)
      {
        throw new Error('"serviceName" should satisfy the constraint - "MaxLength": 50');
      }
      if (serviceName.length < 1)
      {
        throw new Error('"serviceName" should satisfy the constraint - "MinLength": 1');
      }
      if (serviceName.match(/^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/) === null)
      {
        throw new Error('"serviceName" should satisfy the constraint - "Pattern": /^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/');
      }
    }
    if (sid === null || sid === undefined || typeof sid.valueOf() !== 'string') {
      throw new Error('sid cannot be null or undefined and it must be of type string.');
    }
    if (sid !== null && sid !== undefined) {
      if (sid.length > 256)
      {
        throw new Error('"sid" should satisfy the constraint - "MaxLength": 256');
      }
      if (sid.match(/^[^*#&+:<>?]+$/) === null)
      {
        throw new Error('"sid" should satisfy the constraint - "Pattern": /^[^*#&+:<>?]+$/');
      }
    }
    if (ifMatch === null || ifMatch === undefined || typeof ifMatch.valueOf() !== 'string') {
      throw new Error('ifMatch cannot be null or undefined and it must be of type string.');
    }
    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.ApiManagement/service/{serviceName}/subscriptions/{sid}';
  requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
  requestUrl = requestUrl.replace('{serviceName}', encodeURIComponent(serviceName));
  requestUrl = requestUrl.replace('{sid}', encodeURIComponent(sid));
  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 (ifMatch !== undefined && ifMatch !== null) {
    httpRequest.headers['If-Match'] = ifMatch;
  }
  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);
  });
}

/**
 * Regenerates primary key of existing subscription of the API Management
 * service instance.
 *
 * @param {string} resourceGroupName The name of the resource group.
 *
 * @param {string} serviceName The name of the API Management service.
 *
 * @param {string} sid Subscription entity Identifier. The entity represents
 * the association between a user and a product in API Management.
 *
 * @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 _regeneratePrimaryKey(resourceGroupName, serviceName, sid, 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 (serviceName === null || serviceName === undefined || typeof serviceName.valueOf() !== 'string') {
      throw new Error('serviceName cannot be null or undefined and it must be of type string.');
    }
    if (serviceName !== null && serviceName !== undefined) {
      if (serviceName.length > 50)
      {
        throw new Error('"serviceName" should satisfy the constraint - "MaxLength": 50');
      }
      if (serviceName.length < 1)
      {
        throw new Error('"serviceName" should satisfy the constraint - "MinLength": 1');
      }
      if (serviceName.match(/^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/) === null)
      {
        throw new Error('"serviceName" should satisfy the constraint - "Pattern": /^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/');
      }
    }
    if (sid === null || sid === undefined || typeof sid.valueOf() !== 'string') {
      throw new Error('sid cannot be null or undefined and it must be of type string.');
    }
    if (sid !== null && sid !== undefined) {
      if (sid.length > 256)
      {
        throw new Error('"sid" should satisfy the constraint - "MaxLength": 256');
      }
      if (sid.match(/^[^*#&+:<>?]+$/) === null)
      {
        throw new Error('"sid" should satisfy the constraint - "Pattern": /^[^*#&+:<>?]+$/');
      }
    }
    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.ApiManagement/service/{serviceName}/subscriptions/{sid}/regeneratePrimaryKey';
  requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
  requestUrl = requestUrl.replace('{serviceName}', encodeURIComponent(serviceName));
  requestUrl = requestUrl.replace('{sid}', encodeURIComponent(sid));
  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 = '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 !== 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);
  });
}

/**
 * Regenerates secondary key of existing subscription of the API Management
 * service instance.
 *
 * @param {string} resourceGroupName The name of the resource group.
 *
 * @param {string} serviceName The name of the API Management service.
 *
 * @param {string} sid Subscription entity Identifier. The entity represents
 * the association between a user and a product in API Management.
 *
 * @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 _regenerateSecondaryKey(resourceGroupName, serviceName, sid, 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 (serviceName === null || serviceName === undefined || typeof serviceName.valueOf() !== 'string') {
      throw new Error('serviceName cannot be null or undefined and it must be of type string.');
    }
    if (serviceName !== null && serviceName !== undefined) {
      if (serviceName.length > 50)
      {
        throw new Error('"serviceName" should satisfy the constraint - "MaxLength": 50');
      }
      if (serviceName.length < 1)
      {
        throw new Error('"serviceName" should satisfy the constraint - "MinLength": 1');
      }
      if (serviceName.match(/^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/) === null)
      {
        throw new Error('"serviceName" should satisfy the constraint - "Pattern": /^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/');
      }
    }
    if (sid === null || sid === undefined || typeof sid.valueOf() !== 'string') {
      throw new Error('sid cannot be null or undefined and it must be of type string.');
    }
    if (sid !== null && sid !== undefined) {
      if (sid.length > 256)
      {
        throw new Error('"sid" should satisfy the constraint - "MaxLength": 256');
      }
      if (sid.match(/^[^*#&+:<>?]+$/) === null)
      {
        throw new Error('"sid" should satisfy the constraint - "Pattern": /^[^*#&+:<>?]+$/');
      }
    }
    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.ApiManagement/service/{serviceName}/subscriptions/{sid}/regenerateSecondaryKey';
  requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
  requestUrl = requestUrl.replace('{serviceName}', encodeURIComponent(serviceName));
  requestUrl = requestUrl.replace('{sid}', encodeURIComponent(sid));
  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 = '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 !== 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);
  });
}

/**
 * Gets the subscription keys.
 *
 * @param {string} resourceGroupName The name of the resource group.
 *
 * @param {string} serviceName The name of the API Management service.
 *
 * @param {string} sid Subscription entity Identifier. The entity represents
 * the association between a user and a product in API Management.
 *
 * @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 SubscriptionKeysContract} 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 _listSecrets(resourceGroupName, serviceName, sid, 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 (serviceName === null || serviceName === undefined || typeof serviceName.valueOf() !== 'string') {
      throw new Error('serviceName cannot be null or undefined and it must be of type string.');
    }
    if (serviceName !== null && serviceName !== undefined) {
      if (serviceName.length > 50)
      {
        throw new Error('"serviceName" should satisfy the constraint - "MaxLength": 50');
      }
      if (serviceName.length < 1)
      {
        throw new Error('"serviceName" should satisfy the constraint - "MinLength": 1');
      }
      if (serviceName.match(/^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/) === null)
      {
        throw new Error('"serviceName" should satisfy the constraint - "Pattern": /^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/');
      }
    }
    if (sid === null || sid === undefined || typeof sid.valueOf() !== 'string') {
      throw new Error('sid cannot be null or undefined and it must be of type string.');
    }
    if (sid !== null && sid !== undefined) {
      if (sid.length > 256)
      {
        throw new Error('"sid" should satisfy the constraint - "MaxLength": 256');
      }
      if (sid.match(/^[^*#&+:<>?]+$/) === null)
      {
        throw new Error('"sid" should satisfy the constraint - "Pattern": /^[^*#&+:<>?]+$/');
      }
    }
    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.ApiManagement/service/{serviceName}/subscriptions/{sid}/listSecrets';
  requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
  requestUrl = requestUrl.replace('{serviceName}', encodeURIComponent(serviceName));
  requestUrl = requestUrl.replace('{sid}', encodeURIComponent(sid));
  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 = '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) {
      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['SubscriptionKeysContract']().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);
  });
}

/**
 * Lists all subscriptions of the API Management service instance.
 *
 * @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 SubscriptionCollection} 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 _listNext(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['SubscriptionCollection']().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 Subscription. */
class Subscription {
  /**
   * Create a Subscription.
   * @param {ApiManagementClient} client Reference to the service client.
   */
  constructor(client) {
    this.client = client;
    this._list = _list;
    this._getEntityTag = _getEntityTag;
    this._get = _get;
    this._createOrUpdate = _createOrUpdate;
    this._update = _update;
    this._deleteMethod = _deleteMethod;
    this._regeneratePrimaryKey = _regeneratePrimaryKey;
    this._regenerateSecondaryKey = _regenerateSecondaryKey;
    this._listSecrets = _listSecrets;
    this._listNext = _listNext;
  }

  /**
   * Lists all subscriptions of the API Management service instance.
   *
   * @param {string} resourceGroupName The name of the resource group.
   *
   * @param {string} serviceName The name of the API Management service.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {string} [options.filter] |   Field     |     Usage     |
   * Supported operators     |     Supported functions
   * |</br>|-------------|-------------|-------------|-------------|</br>| name |
   * filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
   * endswith | </br>| displayName | filter | ge, le, eq, ne, gt, lt |
   * substringof, contains, startswith, endswith | </br>| stateComment | filter |
   * ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |
   * </br>| ownerId | filter | ge, le, eq, ne, gt, lt | substringof, contains,
   * startswith, endswith | </br>| scope | filter | ge, le, eq, ne, gt, lt |
   * substringof, contains, startswith, endswith | </br>| userId | filter | ge,
   * le, eq, ne, gt, lt | substringof, contains, startswith, endswith | </br>|
   * productId | filter | ge, le, eq, ne, gt, lt | substringof, contains,
   * startswith, endswith | </br>| state | filter | eq |     | </br>| user |
   * expand |     |     | </br>
   *
   * @param {number} [options.top] Number of records to return.
   *
   * @param {number} [options.skip] Number of records to skip.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<SubscriptionCollection>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  listWithHttpOperationResponse(resourceGroupName, serviceName, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._list(resourceGroupName, serviceName, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Lists all subscriptions of the API Management service instance.
   *
   * @param {string} resourceGroupName The name of the resource group.
   *
   * @param {string} serviceName The name of the API Management service.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {string} [options.filter] |   Field     |     Usage     |
   * Supported operators     |     Supported functions
   * |</br>|-------------|-------------|-------------|-------------|</br>| name |
   * filter | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
   * endswith | </br>| displayName | filter | ge, le, eq, ne, gt, lt |
   * substringof, contains, startswith, endswith | </br>| stateComment | filter |
   * ge, le, eq, ne, gt, lt | substringof, contains, startswith, endswith |
   * </br>| ownerId | filter | ge, le, eq, ne, gt, lt | substringof, contains,
   * startswith, endswith | </br>| scope | filter | ge, le, eq, ne, gt, lt |
   * substringof, contains, startswith, endswith | </br>| userId | filter | ge,
   * le, eq, ne, gt, lt | substringof, contains, startswith, endswith | </br>|
   * productId | filter | ge, le, eq, ne, gt, lt | substringof, contains,
   * startswith, endswith | </br>| state | filter | eq |     | </br>| user |
   * expand |     |     | </br>
   *
   * @param {number} [options.top] Number of records to return.
   *
   * @param {number} [options.skip] Number of records to skip.
   *
   * @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 {SubscriptionCollection} - 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 SubscriptionCollection} 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.
   */
  list(resourceGroupName, serviceName, 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._list(resourceGroupName, serviceName, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._list(resourceGroupName, serviceName, options, optionalCallback);
    }
  }

  /**
   * Gets the entity state (Etag) version of the apimanagement subscription
   * specified by its identifier.
   *
   * @param {string} resourceGroupName The name of the resource group.
   *
   * @param {string} serviceName The name of the API Management service.
   *
   * @param {string} sid Subscription entity Identifier. The entity represents
   * the association between a user and a product in API Management.
   *
   * @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.
   */
  getEntityTagWithHttpOperationResponse(resourceGroupName, serviceName, sid, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._getEntityTag(resourceGroupName, serviceName, sid, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Gets the entity state (Etag) version of the apimanagement subscription
   * specified by its identifier.
   *
   * @param {string} resourceGroupName The name of the resource group.
   *
   * @param {string} serviceName The name of the API Management service.
   *
   * @param {string} sid Subscription entity Identifier. The entity represents
   * the association between a user and a product in API Management.
   *
   * @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.
   */
  getEntityTag(resourceGroupName, serviceName, sid, 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._getEntityTag(resourceGroupName, serviceName, sid, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._getEntityTag(resourceGroupName, serviceName, sid, options, optionalCallback);
    }
  }

  /**
   * Gets the specified Subscription entity.
   *
   * @param {string} resourceGroupName The name of the resource group.
   *
   * @param {string} serviceName The name of the API Management service.
   *
   * @param {string} sid Subscription entity Identifier. The entity represents
   * the association between a user and a product in API Management.
   *
   * @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<SubscriptionContract>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  getWithHttpOperationResponse(resourceGroupName, serviceName, sid, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._get(resourceGroupName, serviceName, sid, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Gets the specified Subscription entity.
   *
   * @param {string} resourceGroupName The name of the resource group.
   *
   * @param {string} serviceName The name of the API Management service.
   *
   * @param {string} sid Subscription entity Identifier. The entity represents
   * the association between a user and a product in API Management.
   *
   * @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 {SubscriptionContract} - 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 SubscriptionContract} 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, serviceName, sid, 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, serviceName, sid, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._get(resourceGroupName, serviceName, sid, options, optionalCallback);
    }
  }

  /**
   * Creates or updates the subscription of specified user to the specified
   * product.
   *
   * @param {string} resourceGroupName The name of the resource group.
   *
   * @param {string} serviceName The name of the API Management service.
   *
   * @param {string} sid Subscription entity Identifier. The entity represents
   * the association between a user and a product in API Management.
   *
   * @param {object} parameters Create parameters.
   *
   * @param {string} [parameters.ownerId] User (user id path) for whom
   * subscription is being created in form /users/{userId}
   *
   * @param {string} parameters.scope Scope like /products/{productId} or /apis
   * or /apis/{apiId}.
   *
   * @param {string} parameters.displayName Subscription name.
   *
   * @param {string} [parameters.primaryKey] Primary subscription key. If not
   * specified during request key will be generated automatically.
   *
   * @param {string} [parameters.secondaryKey] Secondary subscription key. If not
   * specified during request key will be generated automatically.
   *
   * @param {string} [parameters.state] Initial subscription state. If no value
   * is specified, subscription is created with Submitted state. Possible states
   * are * active – the subscription is active, * suspended – the subscription is
   * blocked, and the subscriber cannot call any APIs of the product, * submitted
   * – the subscription request has been made by the developer, but has not yet
   * been approved or rejected, * rejected – the subscription request has been
   * denied by an administrator, * cancelled – the subscription has been
   * cancelled by the developer or administrator, * expired – the subscription
   * reached its expiration date and was deactivated. Possible values include:
   * 'suspended', 'active', 'expired', 'submitted', 'rejected', 'cancelled'
   *
   * @param {boolean} [parameters.allowTracing] Determines whether tracing can be
   * enabled
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {boolean} [options.notify] Notify change in Subscription State.
   * - If false, do not send any email notification for change of state of
   * subscription
   * - If true, send email notification of change of state of subscription
   *
   * @param {string} [options.ifMatch] ETag of the Entity. Not required when
   * creating an entity, but required when updating an entity.
   *
   * @param {string} [options.appType] Determines the type of application which
   * send the create user request. Default is legacy publisher portal. Possible
   * values include: 'portal', 'developerPortal'
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<SubscriptionContract>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  createOrUpdateWithHttpOperationResponse(resourceGroupName, serviceName, sid, parameters, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._createOrUpdate(resourceGroupName, serviceName, sid, 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 or updates the subscription of specified user to the specified
   * product.
   *
   * @param {string} resourceGroupName The name of the resource group.
   *
   * @param {string} serviceName The name of the API Management service.
   *
   * @param {string} sid Subscription entity Identifier. The entity represents
   * the association between a user and a product in API Management.
   *
   * @param {object} parameters Create parameters.
   *
   * @param {string} [parameters.ownerId] User (user id path) for whom
   * subscription is being created in form /users/{userId}
   *
   * @param {string} parameters.scope Scope like /products/{productId} or /apis
   * or /apis/{apiId}.
   *
   * @param {string} parameters.displayName Subscription name.
   *
   * @param {string} [parameters.primaryKey] Primary subscription key. If not
   * specified during request key will be generated automatically.
   *
   * @param {string} [parameters.secondaryKey] Secondary subscription key. If not
   * specified during request key will be generated automatically.
   *
   * @param {string} [parameters.state] Initial subscription state. If no value
   * is specified, subscription is created with Submitted state. Possible states
   * are * active – the subscription is active, * suspended – the subscription is
   * blocked, and the subscriber cannot call any APIs of the product, * submitted
   * – the subscription request has been made by the developer, but has not yet
   * been approved or rejected, * rejected – the subscription request has been
   * denied by an administrator, * cancelled – the subscription has been
   * cancelled by the developer or administrator, * expired – the subscription
   * reached its expiration date and was deactivated. Possible values include:
   * 'suspended', 'active', 'expired', 'submitted', 'rejected', 'cancelled'
   *
   * @param {boolean} [parameters.allowTracing] Determines whether tracing can be
   * enabled
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {boolean} [options.notify] Notify change in Subscription State.
   * - If false, do not send any email notification for change of state of
   * subscription
   * - If true, send email notification of change of state of subscription
   *
   * @param {string} [options.ifMatch] ETag of the Entity. Not required when
   * creating an entity, but required when updating an entity.
   *
   * @param {string} [options.appType] Determines the type of application which
   * send the create user request. Default is legacy publisher portal. Possible
   * values include: 'portal', 'developerPortal'
   *
   * @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 {SubscriptionContract} - 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 SubscriptionContract} 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, serviceName, sid, 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, serviceName, sid, parameters, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._createOrUpdate(resourceGroupName, serviceName, sid, parameters, options, optionalCallback);
    }
  }

  /**
   * Updates the details of a subscription specified by its identifier.
   *
   * @param {string} resourceGroupName The name of the resource group.
   *
   * @param {string} serviceName The name of the API Management service.
   *
   * @param {string} sid Subscription entity Identifier. The entity represents
   * the association between a user and a product in API Management.
   *
   * @param {object} parameters Update parameters.
   *
   * @param {string} [parameters.ownerId] User identifier path: /users/{userId}
   *
   * @param {string} [parameters.scope] Scope like /products/{productId} or /apis
   * or /apis/{apiId}
   *
   * @param {date} [parameters.expirationDate] Subscription expiration date. The
   * setting is for audit purposes only and the subscription is not automatically
   * expired. The subscription lifecycle can be managed by using the `state`
   * property. The date conforms to the following format: `yyyy-MM-ddTHH:mm:ssZ`
   * as specified by the ISO 8601 standard.
   *
   * @param {string} [parameters.displayName] Subscription name.
   *
   * @param {string} [parameters.primaryKey] Primary subscription key.
   *
   * @param {string} [parameters.secondaryKey] Secondary subscription key.
   *
   * @param {string} [parameters.state] Subscription state. Possible states are *
   * active – the subscription is active, * suspended – the subscription is
   * blocked, and the subscriber cannot call any APIs of the product, * submitted
   * – the subscription request has been made by the developer, but has not yet
   * been approved or rejected, * rejected – the subscription request has been
   * denied by an administrator, * cancelled – the subscription has been
   * cancelled by the developer or administrator, * expired – the subscription
   * reached its expiration date and was deactivated. Possible values include:
   * 'suspended', 'active', 'expired', 'submitted', 'rejected', 'cancelled'
   *
   * @param {string} [parameters.stateComment] Comments describing subscription
   * state change by the administrator when the state is changed to the
   * 'rejected'.
   *
   * @param {boolean} [parameters.allowTracing] Determines whether tracing can be
   * enabled
   *
   * @param {string} ifMatch ETag of the Entity. ETag should match the current
   * entity state from the header response of the GET request or it should be *
   * for unconditional update.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {boolean} [options.notify] Notify change in Subscription State.
   * - If false, do not send any email notification for change of state of
   * subscription
   * - If true, send email notification of change of state of subscription
   *
   * @param {string} [options.appType] Determines the type of application which
   * send the create user request. Default is legacy publisher portal. Possible
   * values include: 'portal', 'developerPortal'
   *
   * @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.
   */
  updateWithHttpOperationResponse(resourceGroupName, serviceName, sid, parameters, ifMatch, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._update(resourceGroupName, serviceName, sid, parameters, ifMatch, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Updates the details of a subscription specified by its identifier.
   *
   * @param {string} resourceGroupName The name of the resource group.
   *
   * @param {string} serviceName The name of the API Management service.
   *
   * @param {string} sid Subscription entity Identifier. The entity represents
   * the association between a user and a product in API Management.
   *
   * @param {object} parameters Update parameters.
   *
   * @param {string} [parameters.ownerId] User identifier path: /users/{userId}
   *
   * @param {string} [parameters.scope] Scope like /products/{productId} or /apis
   * or /apis/{apiId}
   *
   * @param {date} [parameters.expirationDate] Subscription expiration date. The
   * setting is for audit purposes only and the subscription is not automatically
   * expired. The subscription lifecycle can be managed by using the `state`
   * property. The date conforms to the following format: `yyyy-MM-ddTHH:mm:ssZ`
   * as specified by the ISO 8601 standard.
   *
   * @param {string} [parameters.displayName] Subscription name.
   *
   * @param {string} [parameters.primaryKey] Primary subscription key.
   *
   * @param {string} [parameters.secondaryKey] Secondary subscription key.
   *
   * @param {string} [parameters.state] Subscription state. Possible states are *
   * active – the subscription is active, * suspended – the subscription is
   * blocked, and the subscriber cannot call any APIs of the product, * submitted
   * – the subscription request has been made by the developer, but has not yet
   * been approved or rejected, * rejected – the subscription request has been
   * denied by an administrator, * cancelled – the subscription has been
   * cancelled by the developer or administrator, * expired – the subscription
   * reached its expiration date and was deactivated. Possible values include:
   * 'suspended', 'active', 'expired', 'submitted', 'rejected', 'cancelled'
   *
   * @param {string} [parameters.stateComment] Comments describing subscription
   * state change by the administrator when the state is changed to the
   * 'rejected'.
   *
   * @param {boolean} [parameters.allowTracing] Determines whether tracing can be
   * enabled
   *
   * @param {string} ifMatch ETag of the Entity. ETag should match the current
   * entity state from the header response of the GET request or it should be *
   * for unconditional update.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {boolean} [options.notify] Notify change in Subscription State.
   * - If false, do not send any email notification for change of state of
   * subscription
   * - If true, send email notification of change of state of subscription
   *
   * @param {string} [options.appType] Determines the type of application which
   * send the create user request. Default is legacy publisher portal. Possible
   * values include: 'portal', 'developerPortal'
   *
   * @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.
   */
  update(resourceGroupName, serviceName, sid, parameters, ifMatch, 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._update(resourceGroupName, serviceName, sid, parameters, ifMatch, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._update(resourceGroupName, serviceName, sid, parameters, ifMatch, options, optionalCallback);
    }
  }

  /**
   * Deletes the specified subscription.
   *
   * @param {string} resourceGroupName The name of the resource group.
   *
   * @param {string} serviceName The name of the API Management service.
   *
   * @param {string} sid Subscription entity Identifier. The entity represents
   * the association between a user and a product in API Management.
   *
   * @param {string} ifMatch ETag of the Entity. ETag should match the current
   * entity state from the header response of the GET request or it should be *
   * for unconditional update.
   *
   * @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, serviceName, sid, ifMatch, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._deleteMethod(resourceGroupName, serviceName, sid, ifMatch, 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 specified subscription.
   *
   * @param {string} resourceGroupName The name of the resource group.
   *
   * @param {string} serviceName The name of the API Management service.
   *
   * @param {string} sid Subscription entity Identifier. The entity represents
   * the association between a user and a product in API Management.
   *
   * @param {string} ifMatch ETag of the Entity. ETag should match the current
   * entity state from the header response of the GET request or it should be *
   * for unconditional update.
   *
   * @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, serviceName, sid, ifMatch, 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, serviceName, sid, ifMatch, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._deleteMethod(resourceGroupName, serviceName, sid, ifMatch, options, optionalCallback);
    }
  }

  /**
   * Regenerates primary key of existing subscription of the API Management
   * service instance.
   *
   * @param {string} resourceGroupName The name of the resource group.
   *
   * @param {string} serviceName The name of the API Management service.
   *
   * @param {string} sid Subscription entity Identifier. The entity represents
   * the association between a user and a product in API Management.
   *
   * @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.
   */
  regeneratePrimaryKeyWithHttpOperationResponse(resourceGroupName, serviceName, sid, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._regeneratePrimaryKey(resourceGroupName, serviceName, sid, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Regenerates primary key of existing subscription of the API Management
   * service instance.
   *
   * @param {string} resourceGroupName The name of the resource group.
   *
   * @param {string} serviceName The name of the API Management service.
   *
   * @param {string} sid Subscription entity Identifier. The entity represents
   * the association between a user and a product in API Management.
   *
   * @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.
   */
  regeneratePrimaryKey(resourceGroupName, serviceName, sid, 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._regeneratePrimaryKey(resourceGroupName, serviceName, sid, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._regeneratePrimaryKey(resourceGroupName, serviceName, sid, options, optionalCallback);
    }
  }

  /**
   * Regenerates secondary key of existing subscription of the API Management
   * service instance.
   *
   * @param {string} resourceGroupName The name of the resource group.
   *
   * @param {string} serviceName The name of the API Management service.
   *
   * @param {string} sid Subscription entity Identifier. The entity represents
   * the association between a user and a product in API Management.
   *
   * @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.
   */
  regenerateSecondaryKeyWithHttpOperationResponse(resourceGroupName, serviceName, sid, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._regenerateSecondaryKey(resourceGroupName, serviceName, sid, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Regenerates secondary key of existing subscription of the API Management
   * service instance.
   *
   * @param {string} resourceGroupName The name of the resource group.
   *
   * @param {string} serviceName The name of the API Management service.
   *
   * @param {string} sid Subscription entity Identifier. The entity represents
   * the association between a user and a product in API Management.
   *
   * @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.
   */
  regenerateSecondaryKey(resourceGroupName, serviceName, sid, 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._regenerateSecondaryKey(resourceGroupName, serviceName, sid, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._regenerateSecondaryKey(resourceGroupName, serviceName, sid, options, optionalCallback);
    }
  }

  /**
   * Gets the subscription keys.
   *
   * @param {string} resourceGroupName The name of the resource group.
   *
   * @param {string} serviceName The name of the API Management service.
   *
   * @param {string} sid Subscription entity Identifier. The entity represents
   * the association between a user and a product in API Management.
   *
   * @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<SubscriptionKeysContract>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  listSecretsWithHttpOperationResponse(resourceGroupName, serviceName, sid, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._listSecrets(resourceGroupName, serviceName, sid, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Gets the subscription keys.
   *
   * @param {string} resourceGroupName The name of the resource group.
   *
   * @param {string} serviceName The name of the API Management service.
   *
   * @param {string} sid Subscription entity Identifier. The entity represents
   * the association between a user and a product in API Management.
   *
   * @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 {SubscriptionKeysContract} - 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 SubscriptionKeysContract} 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.
   */
  listSecrets(resourceGroupName, serviceName, sid, 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._listSecrets(resourceGroupName, serviceName, sid, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._listSecrets(resourceGroupName, serviceName, sid, options, optionalCallback);
    }
  }

  /**
   * Lists all subscriptions of the API Management service instance.
   *
   * @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<SubscriptionCollection>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  listNextWithHttpOperationResponse(nextPageLink, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._listNext(nextPageLink, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Lists all subscriptions of the API Management service instance.
   *
   * @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 {SubscriptionCollection} - 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 SubscriptionCollection} 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.
   */
  listNext(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._listNext(nextPageLink, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._listNext(nextPageLink, options, optionalCallback);
    }
  }

}

module.exports = Subscription;
