/*
 * 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 APIs 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       | Supported operators    |
 * Supported functions               |
 * |-------------|------------------------|-----------------------------------|
 * | id          | ge, le, eq, ne, gt, lt | substringof, startswith, endswith |
 * | name        | ge, le, eq, ne, gt, lt | substringof, startswith, endswith |
 * | description | ge, le, eq, ne, gt, lt | substringof, startswith, endswith |
 * | serviceUrl  | ge, le, eq, ne, gt, lt | substringof, startswith, endswith |
 * | path        | ge, le, eq, ne, gt, lt | substringof, startswith, endswith |
 *
 * @param {number} [options.top] Number of records to return.
 *
 * @param {number} [options.skip] Number of records to skip.
 *
 * @param {boolean} [options.expandApiVersionSet] Include full ApiVersionSet
 * resource in response
 *
 * @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 ApiCollection} 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 _listByService(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;
  let expandApiVersionSet = (options && options.expandApiVersionSet !== undefined) ? options.expandApiVersionSet : false;
  // 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 (expandApiVersionSet !== null && expandApiVersionSet !== undefined && typeof expandApiVersionSet !== 'boolean') {
      throw new Error('expandApiVersionSet must be of type boolean.');
    }
    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}/apis';
  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 (expandApiVersionSet !== null && expandApiVersionSet !== undefined) {
    queryParameters.push('expandApiVersionSet=' + encodeURIComponent(expandApiVersionSet.toString()));
  }
  if (queryParameters.length > 0) {
    requestUrl += '?' + queryParameters.join('&');
  }

  // Create HTTP transport objects
  let httpRequest = new WebResource();
  httpRequest.method = 'GET';
  httpRequest.url = requestUrl;
  httpRequest.headers = {};
  // Set Headers
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  if (this.client.generateClientRequestId) {
      httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if(options) {
    for(let headerName in options['customHeaders']) {
      if (options['customHeaders'].hasOwnProperty(headerName)) {
        httpRequest.headers[headerName] = options['customHeaders'][headerName];
      }
    }
  }
  httpRequest.body = null;
  // Send Request
  return client.pipeline(httpRequest, (err, response, responseBody) => {
    if (err) {
      return callback(err);
    }
    let statusCode = response.statusCode;
    if (statusCode !== 200) {
      let error = new Error(responseBody);
      error.statusCode = response.statusCode;
      error.request = msRest.stripRequest(httpRequest);
      error.response = msRest.stripResponse(response);
      if (responseBody === '') responseBody = null;
      let parsedErrorResponse;
      try {
        parsedErrorResponse = JSON.parse(responseBody);
        if (parsedErrorResponse) {
          let internalError = null;
          if (parsedErrorResponse.error) internalError = parsedErrorResponse.error;
          error.code = internalError ? internalError.code : parsedErrorResponse.code;
          error.message = internalError ? internalError.message : parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          let resultMapper = new client.models['ErrorResponse']().mapper();
          error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
        }
      } catch (defaultError) {
        error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
                         `- "${responseBody}" for the default response.`;
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    let result = null;
    if (responseBody === '') responseBody = null;
    // Deserialize Response
    if (statusCode === 200) {
      let parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          let resultMapper = new client.models['ApiCollection']().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 API 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} apiId API revision identifier. Must be unique in the current
 * API Management service instance. Non-current revision has ;rev=n as a suffix
 * where n is the revision number.
 *
 * @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, apiId, 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 (apiId === null || apiId === undefined || typeof apiId.valueOf() !== 'string') {
      throw new Error('apiId cannot be null or undefined and it must be of type string.');
    }
    if (apiId !== null && apiId !== undefined) {
      if (apiId.length > 256)
      {
        throw new Error('"apiId" should satisfy the constraint - "MaxLength": 256');
      }
      if (apiId.length < 1)
      {
        throw new Error('"apiId" should satisfy the constraint - "MinLength": 1');
      }
      if (apiId.match(/^[^*#&+:<>?]+$/) === null)
      {
        throw new Error('"apiId" 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}/apis/{apiId}';
  requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
  requestUrl = requestUrl.replace('{serviceName}', encodeURIComponent(serviceName));
  requestUrl = requestUrl.replace('{apiId}', encodeURIComponent(apiId));
  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 details of the API 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} apiId API revision identifier. Must be unique in the current
 * API Management service instance. Non-current revision has ;rev=n as a suffix
 * where n is the revision number.
 *
 * @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 ApiContract} 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, apiId, 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 (apiId === null || apiId === undefined || typeof apiId.valueOf() !== 'string') {
      throw new Error('apiId cannot be null or undefined and it must be of type string.');
    }
    if (apiId !== null && apiId !== undefined) {
      if (apiId.length > 256)
      {
        throw new Error('"apiId" should satisfy the constraint - "MaxLength": 256');
      }
      if (apiId.length < 1)
      {
        throw new Error('"apiId" should satisfy the constraint - "MinLength": 1');
      }
      if (apiId.match(/^[^*#&+:<>?]+$/) === null)
      {
        throw new Error('"apiId" 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}/apis/{apiId}';
  requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
  requestUrl = requestUrl.replace('{serviceName}', encodeURIComponent(serviceName));
  requestUrl = requestUrl.replace('{apiId}', encodeURIComponent(apiId));
  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['ApiContract']().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 new or updates existing specified API 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} apiId API revision identifier. Must be unique in the current
 * API Management service instance. Non-current revision has ;rev=n as a suffix
 * where n is the revision number.
 *
 * @param {object} parameters Create or update parameters.
 *
 * @param {string} [parameters.description] Description of the API. May include
 * HTML formatting tags.
 *
 * @param {object} [parameters.authenticationSettings] Collection of
 * authentication settings included into this API.
 *
 * @param {object} [parameters.authenticationSettings.oAuth2] OAuth2
 * Authentication settings
 *
 * @param {string}
 * [parameters.authenticationSettings.oAuth2.authorizationServerId] OAuth
 * authorization server identifier.
 *
 * @param {string} [parameters.authenticationSettings.oAuth2.scope] operations
 * scope.
 *
 * @param {object} [parameters.subscriptionKeyParameterNames] Protocols over
 * which API is made available.
 *
 * @param {string} [parameters.subscriptionKeyParameterNames.header]
 * Subscription key header name.
 *
 * @param {string} [parameters.subscriptionKeyParameterNames.query]
 * Subscription key query string parameter name.
 *
 * @param {string} [parameters.apiType] Type of API. Possible values include:
 * 'http', 'soap'
 *
 * @param {string} [parameters.apiRevision] Describes the Revision of the Api.
 * If no value is provided, default revision 1 is created
 *
 * @param {string} [parameters.apiVersion] Indicates the Version identifier of
 * the API if the API is versioned
 *
 * @param {string} [parameters.apiVersionSetId] A resource identifier for the
 * related ApiVersionSet.
 *
 * @param {string} [parameters.displayName] API name.
 *
 * @param {string} [parameters.serviceUrl] Absolute URL of the backend service
 * implementing this API.
 *
 * @param {string} parameters.path Relative URL uniquely identifying this API
 * and all of its resource paths within the API Management service instance. It
 * is appended to the API endpoint base URL specified during the service
 * instance creation to form a public URL for this API.
 *
 * @param {array} [parameters.protocols] Describes on which protocols the
 * operations in this API can be invoked.
 *
 * @param {object} [parameters.apiVersionSet]
 *
 * @param {string} [parameters.apiVersionSet.id] Identifier for existing API
 * Version Set. Omit this value to create a new Version Set.
 *
 * @param {string} [parameters.apiVersionSet.description] Description of API
 * Version Set.
 *
 * @param {string} [parameters.apiVersionSet.versioningScheme] An value that
 * determines where the API Version identifer will be located in a HTTP
 * request. Possible values include: 'Segment', 'Query', 'Header'
 *
 * @param {string} [parameters.apiVersionSet.versionQueryName] Name of query
 * parameter that indicates the API Version if versioningScheme is set to
 * `query`.
 *
 * @param {string} [parameters.apiVersionSet.versionHeaderName] Name of HTTP
 * header parameter that indicates the API Version if versioningScheme is set
 * to `header`.
 *
 * @param {string} [parameters.contentValue] Content value when Importing an
 * API.
 *
 * @param {string} [parameters.contentFormat] Format of the Content in which
 * the API is getting imported. Possible values include: 'wadl-xml',
 * 'wadl-link-json', 'swagger-json', 'swagger-link-json', 'wsdl', 'wsdl-link'
 *
 * @param {object} [parameters.wsdlSelector] Criteria to limit import of WSDL
 * to a subset of the document.
 *
 * @param {string} [parameters.wsdlSelector.wsdlServiceName] Name of service to
 * import from WSDL
 *
 * @param {string} [parameters.wsdlSelector.wsdlEndpointName] Name of
 * endpoint(port) to import from WSDL
 *
 * @param {string} [parameters.soapApiType] Type of Api to create.
 * * `http` creates a SOAP to REST API
 * * `soap` creates a SOAP pass-through API. Possible values include:
 * 'SoapToRest', 'SoapPassThrough'
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {string} [options.ifMatch] ETag of the Entity. Not required when
 * creating an entity, but required when updating an entity.
 *
 * @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 ApiContract} 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, apiId, 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 ifMatch = (options && options.ifMatch !== undefined) ? options.ifMatch : 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 (apiId === null || apiId === undefined || typeof apiId.valueOf() !== 'string') {
      throw new Error('apiId cannot be null or undefined and it must be of type string.');
    }
    if (apiId !== null && apiId !== undefined) {
      if (apiId.length > 256)
      {
        throw new Error('"apiId" should satisfy the constraint - "MaxLength": 256');
      }
      if (apiId.length < 1)
      {
        throw new Error('"apiId" should satisfy the constraint - "MinLength": 1');
      }
      if (apiId.match(/^[^*#&+:<>?]+$/) === null)
      {
        throw new Error('"apiId" should satisfy the constraint - "Pattern": /^[^*#&+:<>?]+$/');
      }
    }
    if (parameters === null || parameters === undefined) {
      throw new Error('parameters cannot be null or undefined.');
    }
    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 (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}/apis/{apiId}';
  requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
  requestUrl = requestUrl.replace('{serviceName}', encodeURIComponent(serviceName));
  requestUrl = requestUrl.replace('{apiId}', encodeURIComponent(apiId));
  requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
  let queryParameters = [];
  queryParameters.push('api-version=' + encodeURIComponent(this.client.apiVersion));
  if (queryParameters.length > 0) {
    requestUrl += '?' + queryParameters.join('&');
  }

  // Create HTTP transport objects
  let httpRequest = new WebResource();
  httpRequest.method = 'PUT';
  httpRequest.url = requestUrl;
  httpRequest.headers = {};
  // Set Headers
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  if (this.client.generateClientRequestId) {
      httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
  }
  if (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['ApiCreateOrUpdateParameter']().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['ApiContract']().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['ApiContract']().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 specified API 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} apiId API revision identifier. Must be unique in the current
 * API Management service instance. Non-current revision has ;rev=n as a suffix
 * where n is the revision number.
 *
 * @param {object} parameters API Update Contract parameters.
 *
 * @param {string} [parameters.description] Description of the API. May include
 * HTML formatting tags.
 *
 * @param {object} [parameters.authenticationSettings] Collection of
 * authentication settings included into this API.
 *
 * @param {object} [parameters.authenticationSettings.oAuth2] OAuth2
 * Authentication settings
 *
 * @param {string}
 * [parameters.authenticationSettings.oAuth2.authorizationServerId] OAuth
 * authorization server identifier.
 *
 * @param {string} [parameters.authenticationSettings.oAuth2.scope] operations
 * scope.
 *
 * @param {object} [parameters.subscriptionKeyParameterNames] Protocols over
 * which API is made available.
 *
 * @param {string} [parameters.subscriptionKeyParameterNames.header]
 * Subscription key header name.
 *
 * @param {string} [parameters.subscriptionKeyParameterNames.query]
 * Subscription key query string parameter name.
 *
 * @param {string} [parameters.apiType] Type of API. Possible values include:
 * 'http', 'soap'
 *
 * @param {string} [parameters.apiRevision] Describes the Revision of the Api.
 * If no value is provided, default revision 1 is created
 *
 * @param {string} [parameters.apiVersion] Indicates the Version identifier of
 * the API if the API is versioned
 *
 * @param {string} [parameters.apiVersionSetId] A resource identifier for the
 * related ApiVersionSet.
 *
 * @param {string} [parameters.displayName] API name.
 *
 * @param {string} [parameters.serviceUrl] Absolute URL of the backend service
 * implementing this API.
 *
 * @param {string} [parameters.path] Relative URL uniquely identifying this API
 * and all of its resource paths within the API Management service instance. It
 * is appended to the API endpoint base URL specified during the service
 * instance creation to form a public URL for this API.
 *
 * @param {array} [parameters.protocols] Describes on which protocols the
 * operations in this API can be invoked.
 *
 * @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 _update(resourceGroupName, serviceName, apiId, 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.');
  }
  // 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 (apiId === null || apiId === undefined || typeof apiId.valueOf() !== 'string') {
      throw new Error('apiId cannot be null or undefined and it must be of type string.');
    }
    if (apiId !== null && apiId !== undefined) {
      if (apiId.length > 256)
      {
        throw new Error('"apiId" should satisfy the constraint - "MaxLength": 256');
      }
      if (apiId.length < 1)
      {
        throw new Error('"apiId" should satisfy the constraint - "MinLength": 1');
      }
      if (apiId.match(/^[^*#&+:<>?]+$/) === null)
      {
        throw new Error('"apiId" should satisfy the constraint - "Pattern": /^[^*#&+:<>?]+$/');
      }
    }
    if (parameters === null || parameters === undefined) {
      throw new Error('parameters cannot be null or undefined.');
    }
    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}/apis/{apiId}';
  requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
  requestUrl = requestUrl.replace('{serviceName}', encodeURIComponent(serviceName));
  requestUrl = requestUrl.replace('{apiId}', encodeURIComponent(apiId));
  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 = '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['ApiUpdateContract']().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 API 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} apiId API revision identifier. Must be unique in the current
 * API Management service instance. Non-current revision has ;rev=n as a suffix
 * where n is the revision number.
 *
 * @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.deleteRevisions] Delete all revisions of the Api.
 *
 * @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, apiId, 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 deleteRevisions = (options && options.deleteRevisions !== undefined) ? options.deleteRevisions : 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 (apiId === null || apiId === undefined || typeof apiId.valueOf() !== 'string') {
      throw new Error('apiId cannot be null or undefined and it must be of type string.');
    }
    if (apiId !== null && apiId !== undefined) {
      if (apiId.length > 256)
      {
        throw new Error('"apiId" should satisfy the constraint - "MaxLength": 256');
      }
      if (apiId.length < 1)
      {
        throw new Error('"apiId" should satisfy the constraint - "MinLength": 1');
      }
      if (apiId.match(/^[^*#&+:<>?]+$/) === null)
      {
        throw new Error('"apiId" should satisfy the constraint - "Pattern": /^[^*#&+:<>?]+$/');
      }
    }
    if (deleteRevisions !== null && deleteRevisions !== undefined && typeof deleteRevisions !== 'boolean') {
      throw new Error('deleteRevisions 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 (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}/apis/{apiId}';
  requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
  requestUrl = requestUrl.replace('{serviceName}', encodeURIComponent(serviceName));
  requestUrl = requestUrl.replace('{apiId}', encodeURIComponent(apiId));
  requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
  let queryParameters = [];
  if (deleteRevisions !== null && deleteRevisions !== undefined) {
    queryParameters.push('deleteRevisions=' + encodeURIComponent(deleteRevisions.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 = '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);
  });
}

/**
 * Lists a collection of apis associated with tags.
 *
 * @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       | Supported operators    |
 * Supported functions                         |
 * |-------------|------------------------|---------------------------------------------|
 * | id          | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
 * endswith |
 * | name        | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
 * endswith |
 * | aid         | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
 * endswith |
 * | apiRevision | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
 * endswith |
 * | path        | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
 * endswith |
 * | description | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
 * endswith |
 * | serviceUrl  | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
 * endswith |
 * | isCurrent   | eq                     | substringof, contains, startswith,
 * endswith |
 *
 * @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 TagResourceCollection} 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 _listByTags(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}/apisByTags';
  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) {
          if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
          if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
          if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          let resultMapper = new client.models['CloudError']().mapper();
          error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
        }
      } catch (defaultError) {
        error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
                         `- "${responseBody}" for the default response.`;
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    let result = null;
    if (responseBody === '') responseBody = null;
    // Deserialize Response
    if (statusCode === 200) {
      let parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          let resultMapper = new client.models['TagResourceCollection']().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 APIs 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 ApiCollection} 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 _listByServiceNext(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['ApiCollection']().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 a collection of apis associated with tags.
 *
 * @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 TagResourceCollection} 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 _listByTagsNext(nextPageLink, options, callback) {
   /* jshint validthis: true */
  let client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }
  // Validate
  try {
    if (nextPageLink === null || nextPageLink === undefined || typeof nextPageLink.valueOf() !== 'string') {
      throw new Error('nextPageLink cannot be null or undefined and it must be of type string.');
    }
    if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
      throw new Error('this.client.acceptLanguage must be of type string.');
    }
  } catch (error) {
    return callback(error);
  }

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

  // Create HTTP transport objects
  let httpRequest = new WebResource();
  httpRequest.method = 'GET';
  httpRequest.url = requestUrl;
  httpRequest.headers = {};
  // Set Headers
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  if (this.client.generateClientRequestId) {
      httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if(options) {
    for(let headerName in options['customHeaders']) {
      if (options['customHeaders'].hasOwnProperty(headerName)) {
        httpRequest.headers[headerName] = options['customHeaders'][headerName];
      }
    }
  }
  httpRequest.body = null;
  // Send Request
  return client.pipeline(httpRequest, (err, response, responseBody) => {
    if (err) {
      return callback(err);
    }
    let statusCode = response.statusCode;
    if (statusCode !== 200) {
      let error = new Error(responseBody);
      error.statusCode = response.statusCode;
      error.request = msRest.stripRequest(httpRequest);
      error.response = msRest.stripResponse(response);
      if (responseBody === '') responseBody = null;
      let parsedErrorResponse;
      try {
        parsedErrorResponse = JSON.parse(responseBody);
        if (parsedErrorResponse) {
          if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
          if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
          if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          let resultMapper = new client.models['CloudError']().mapper();
          error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
        }
      } catch (defaultError) {
        error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
                         `- "${responseBody}" for the default response.`;
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    let result = null;
    if (responseBody === '') responseBody = null;
    // Deserialize Response
    if (statusCode === 200) {
      let parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          let resultMapper = new client.models['TagResourceCollection']().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 Api. */
class Api {
  /**
   * Create a Api.
   * @param {ApiManagementClient} client Reference to the service client.
   */
  constructor(client) {
    this.client = client;
    this._listByService = _listByService;
    this._getEntityTag = _getEntityTag;
    this._get = _get;
    this._createOrUpdate = _createOrUpdate;
    this._update = _update;
    this._deleteMethod = _deleteMethod;
    this._listByTags = _listByTags;
    this._listByServiceNext = _listByServiceNext;
    this._listByTagsNext = _listByTagsNext;
  }

  /**
   * Lists all APIs 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       | Supported operators    |
   * Supported functions               |
   * |-------------|------------------------|-----------------------------------|
   * | id          | ge, le, eq, ne, gt, lt | substringof, startswith, endswith |
   * | name        | ge, le, eq, ne, gt, lt | substringof, startswith, endswith |
   * | description | ge, le, eq, ne, gt, lt | substringof, startswith, endswith |
   * | serviceUrl  | ge, le, eq, ne, gt, lt | substringof, startswith, endswith |
   * | path        | ge, le, eq, ne, gt, lt | substringof, startswith, endswith |
   *
   * @param {number} [options.top] Number of records to return.
   *
   * @param {number} [options.skip] Number of records to skip.
   *
   * @param {boolean} [options.expandApiVersionSet] Include full ApiVersionSet
   * resource in response
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<ApiCollection>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  listByServiceWithHttpOperationResponse(resourceGroupName, serviceName, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._listByService(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 APIs 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       | Supported operators    |
   * Supported functions               |
   * |-------------|------------------------|-----------------------------------|
   * | id          | ge, le, eq, ne, gt, lt | substringof, startswith, endswith |
   * | name        | ge, le, eq, ne, gt, lt | substringof, startswith, endswith |
   * | description | ge, le, eq, ne, gt, lt | substringof, startswith, endswith |
   * | serviceUrl  | ge, le, eq, ne, gt, lt | substringof, startswith, endswith |
   * | path        | ge, le, eq, ne, gt, lt | substringof, startswith, endswith |
   *
   * @param {number} [options.top] Number of records to return.
   *
   * @param {number} [options.skip] Number of records to skip.
   *
   * @param {boolean} [options.expandApiVersionSet] Include full ApiVersionSet
   * resource in response
   *
   * @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 {ApiCollection} - 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 ApiCollection} 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.
   */
  listByService(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._listByService(resourceGroupName, serviceName, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._listByService(resourceGroupName, serviceName, options, optionalCallback);
    }
  }

  /**
   * Gets the entity state (Etag) version of the API 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} apiId API revision identifier. Must be unique in the current
   * API Management service instance. Non-current revision has ;rev=n as a suffix
   * where n is the revision number.
   *
   * @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, apiId, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._getEntityTag(resourceGroupName, serviceName, apiId, 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 API 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} apiId API revision identifier. Must be unique in the current
   * API Management service instance. Non-current revision has ;rev=n as a suffix
   * where n is the revision number.
   *
   * @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, apiId, 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, apiId, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._getEntityTag(resourceGroupName, serviceName, apiId, options, optionalCallback);
    }
  }

  /**
   * Gets the details of the API 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} apiId API revision identifier. Must be unique in the current
   * API Management service instance. Non-current revision has ;rev=n as a suffix
   * where n is the revision number.
   *
   * @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<ApiContract>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  getWithHttpOperationResponse(resourceGroupName, serviceName, apiId, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._get(resourceGroupName, serviceName, apiId, 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 details of the API 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} apiId API revision identifier. Must be unique in the current
   * API Management service instance. Non-current revision has ;rev=n as a suffix
   * where n is the revision number.
   *
   * @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 {ApiContract} - 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 ApiContract} 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, apiId, 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, apiId, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._get(resourceGroupName, serviceName, apiId, options, optionalCallback);
    }
  }

  /**
   * Creates new or updates existing specified API 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} apiId API revision identifier. Must be unique in the current
   * API Management service instance. Non-current revision has ;rev=n as a suffix
   * where n is the revision number.
   *
   * @param {object} parameters Create or update parameters.
   *
   * @param {string} [parameters.description] Description of the API. May include
   * HTML formatting tags.
   *
   * @param {object} [parameters.authenticationSettings] Collection of
   * authentication settings included into this API.
   *
   * @param {object} [parameters.authenticationSettings.oAuth2] OAuth2
   * Authentication settings
   *
   * @param {string}
   * [parameters.authenticationSettings.oAuth2.authorizationServerId] OAuth
   * authorization server identifier.
   *
   * @param {string} [parameters.authenticationSettings.oAuth2.scope] operations
   * scope.
   *
   * @param {object} [parameters.subscriptionKeyParameterNames] Protocols over
   * which API is made available.
   *
   * @param {string} [parameters.subscriptionKeyParameterNames.header]
   * Subscription key header name.
   *
   * @param {string} [parameters.subscriptionKeyParameterNames.query]
   * Subscription key query string parameter name.
   *
   * @param {string} [parameters.apiType] Type of API. Possible values include:
   * 'http', 'soap'
   *
   * @param {string} [parameters.apiRevision] Describes the Revision of the Api.
   * If no value is provided, default revision 1 is created
   *
   * @param {string} [parameters.apiVersion] Indicates the Version identifier of
   * the API if the API is versioned
   *
   * @param {string} [parameters.apiVersionSetId] A resource identifier for the
   * related ApiVersionSet.
   *
   * @param {string} [parameters.displayName] API name.
   *
   * @param {string} [parameters.serviceUrl] Absolute URL of the backend service
   * implementing this API.
   *
   * @param {string} parameters.path Relative URL uniquely identifying this API
   * and all of its resource paths within the API Management service instance. It
   * is appended to the API endpoint base URL specified during the service
   * instance creation to form a public URL for this API.
   *
   * @param {array} [parameters.protocols] Describes on which protocols the
   * operations in this API can be invoked.
   *
   * @param {object} [parameters.apiVersionSet]
   *
   * @param {string} [parameters.apiVersionSet.id] Identifier for existing API
   * Version Set. Omit this value to create a new Version Set.
   *
   * @param {string} [parameters.apiVersionSet.description] Description of API
   * Version Set.
   *
   * @param {string} [parameters.apiVersionSet.versioningScheme] An value that
   * determines where the API Version identifer will be located in a HTTP
   * request. Possible values include: 'Segment', 'Query', 'Header'
   *
   * @param {string} [parameters.apiVersionSet.versionQueryName] Name of query
   * parameter that indicates the API Version if versioningScheme is set to
   * `query`.
   *
   * @param {string} [parameters.apiVersionSet.versionHeaderName] Name of HTTP
   * header parameter that indicates the API Version if versioningScheme is set
   * to `header`.
   *
   * @param {string} [parameters.contentValue] Content value when Importing an
   * API.
   *
   * @param {string} [parameters.contentFormat] Format of the Content in which
   * the API is getting imported. Possible values include: 'wadl-xml',
   * 'wadl-link-json', 'swagger-json', 'swagger-link-json', 'wsdl', 'wsdl-link'
   *
   * @param {object} [parameters.wsdlSelector] Criteria to limit import of WSDL
   * to a subset of the document.
   *
   * @param {string} [parameters.wsdlSelector.wsdlServiceName] Name of service to
   * import from WSDL
   *
   * @param {string} [parameters.wsdlSelector.wsdlEndpointName] Name of
   * endpoint(port) to import from WSDL
   *
   * @param {string} [parameters.soapApiType] Type of Api to create.
   * * `http` creates a SOAP to REST API
   * * `soap` creates a SOAP pass-through API. Possible values include:
   * 'SoapToRest', 'SoapPassThrough'
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {string} [options.ifMatch] ETag of the Entity. Not required when
   * creating an entity, but required when updating an entity.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<ApiContract>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  createOrUpdateWithHttpOperationResponse(resourceGroupName, serviceName, apiId, parameters, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._createOrUpdate(resourceGroupName, serviceName, apiId, 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 new or updates existing specified API 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} apiId API revision identifier. Must be unique in the current
   * API Management service instance. Non-current revision has ;rev=n as a suffix
   * where n is the revision number.
   *
   * @param {object} parameters Create or update parameters.
   *
   * @param {string} [parameters.description] Description of the API. May include
   * HTML formatting tags.
   *
   * @param {object} [parameters.authenticationSettings] Collection of
   * authentication settings included into this API.
   *
   * @param {object} [parameters.authenticationSettings.oAuth2] OAuth2
   * Authentication settings
   *
   * @param {string}
   * [parameters.authenticationSettings.oAuth2.authorizationServerId] OAuth
   * authorization server identifier.
   *
   * @param {string} [parameters.authenticationSettings.oAuth2.scope] operations
   * scope.
   *
   * @param {object} [parameters.subscriptionKeyParameterNames] Protocols over
   * which API is made available.
   *
   * @param {string} [parameters.subscriptionKeyParameterNames.header]
   * Subscription key header name.
   *
   * @param {string} [parameters.subscriptionKeyParameterNames.query]
   * Subscription key query string parameter name.
   *
   * @param {string} [parameters.apiType] Type of API. Possible values include:
   * 'http', 'soap'
   *
   * @param {string} [parameters.apiRevision] Describes the Revision of the Api.
   * If no value is provided, default revision 1 is created
   *
   * @param {string} [parameters.apiVersion] Indicates the Version identifier of
   * the API if the API is versioned
   *
   * @param {string} [parameters.apiVersionSetId] A resource identifier for the
   * related ApiVersionSet.
   *
   * @param {string} [parameters.displayName] API name.
   *
   * @param {string} [parameters.serviceUrl] Absolute URL of the backend service
   * implementing this API.
   *
   * @param {string} parameters.path Relative URL uniquely identifying this API
   * and all of its resource paths within the API Management service instance. It
   * is appended to the API endpoint base URL specified during the service
   * instance creation to form a public URL for this API.
   *
   * @param {array} [parameters.protocols] Describes on which protocols the
   * operations in this API can be invoked.
   *
   * @param {object} [parameters.apiVersionSet]
   *
   * @param {string} [parameters.apiVersionSet.id] Identifier for existing API
   * Version Set. Omit this value to create a new Version Set.
   *
   * @param {string} [parameters.apiVersionSet.description] Description of API
   * Version Set.
   *
   * @param {string} [parameters.apiVersionSet.versioningScheme] An value that
   * determines where the API Version identifer will be located in a HTTP
   * request. Possible values include: 'Segment', 'Query', 'Header'
   *
   * @param {string} [parameters.apiVersionSet.versionQueryName] Name of query
   * parameter that indicates the API Version if versioningScheme is set to
   * `query`.
   *
   * @param {string} [parameters.apiVersionSet.versionHeaderName] Name of HTTP
   * header parameter that indicates the API Version if versioningScheme is set
   * to `header`.
   *
   * @param {string} [parameters.contentValue] Content value when Importing an
   * API.
   *
   * @param {string} [parameters.contentFormat] Format of the Content in which
   * the API is getting imported. Possible values include: 'wadl-xml',
   * 'wadl-link-json', 'swagger-json', 'swagger-link-json', 'wsdl', 'wsdl-link'
   *
   * @param {object} [parameters.wsdlSelector] Criteria to limit import of WSDL
   * to a subset of the document.
   *
   * @param {string} [parameters.wsdlSelector.wsdlServiceName] Name of service to
   * import from WSDL
   *
   * @param {string} [parameters.wsdlSelector.wsdlEndpointName] Name of
   * endpoint(port) to import from WSDL
   *
   * @param {string} [parameters.soapApiType] Type of Api to create.
   * * `http` creates a SOAP to REST API
   * * `soap` creates a SOAP pass-through API. Possible values include:
   * 'SoapToRest', 'SoapPassThrough'
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {string} [options.ifMatch] ETag of the Entity. Not required when
   * creating an entity, but required when updating an entity.
   *
   * @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 {ApiContract} - 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 ApiContract} 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, apiId, 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, apiId, parameters, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._createOrUpdate(resourceGroupName, serviceName, apiId, parameters, options, optionalCallback);
    }
  }

  /**
   * Updates the specified API 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} apiId API revision identifier. Must be unique in the current
   * API Management service instance. Non-current revision has ;rev=n as a suffix
   * where n is the revision number.
   *
   * @param {object} parameters API Update Contract parameters.
   *
   * @param {string} [parameters.description] Description of the API. May include
   * HTML formatting tags.
   *
   * @param {object} [parameters.authenticationSettings] Collection of
   * authentication settings included into this API.
   *
   * @param {object} [parameters.authenticationSettings.oAuth2] OAuth2
   * Authentication settings
   *
   * @param {string}
   * [parameters.authenticationSettings.oAuth2.authorizationServerId] OAuth
   * authorization server identifier.
   *
   * @param {string} [parameters.authenticationSettings.oAuth2.scope] operations
   * scope.
   *
   * @param {object} [parameters.subscriptionKeyParameterNames] Protocols over
   * which API is made available.
   *
   * @param {string} [parameters.subscriptionKeyParameterNames.header]
   * Subscription key header name.
   *
   * @param {string} [parameters.subscriptionKeyParameterNames.query]
   * Subscription key query string parameter name.
   *
   * @param {string} [parameters.apiType] Type of API. Possible values include:
   * 'http', 'soap'
   *
   * @param {string} [parameters.apiRevision] Describes the Revision of the Api.
   * If no value is provided, default revision 1 is created
   *
   * @param {string} [parameters.apiVersion] Indicates the Version identifier of
   * the API if the API is versioned
   *
   * @param {string} [parameters.apiVersionSetId] A resource identifier for the
   * related ApiVersionSet.
   *
   * @param {string} [parameters.displayName] API name.
   *
   * @param {string} [parameters.serviceUrl] Absolute URL of the backend service
   * implementing this API.
   *
   * @param {string} [parameters.path] Relative URL uniquely identifying this API
   * and all of its resource paths within the API Management service instance. It
   * is appended to the API endpoint base URL specified during the service
   * instance creation to form a public URL for this API.
   *
   * @param {array} [parameters.protocols] Describes on which protocols the
   * operations in this API can be invoked.
   *
   * @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.
   */
  updateWithHttpOperationResponse(resourceGroupName, serviceName, apiId, parameters, ifMatch, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._update(resourceGroupName, serviceName, apiId, 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 specified API 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} apiId API revision identifier. Must be unique in the current
   * API Management service instance. Non-current revision has ;rev=n as a suffix
   * where n is the revision number.
   *
   * @param {object} parameters API Update Contract parameters.
   *
   * @param {string} [parameters.description] Description of the API. May include
   * HTML formatting tags.
   *
   * @param {object} [parameters.authenticationSettings] Collection of
   * authentication settings included into this API.
   *
   * @param {object} [parameters.authenticationSettings.oAuth2] OAuth2
   * Authentication settings
   *
   * @param {string}
   * [parameters.authenticationSettings.oAuth2.authorizationServerId] OAuth
   * authorization server identifier.
   *
   * @param {string} [parameters.authenticationSettings.oAuth2.scope] operations
   * scope.
   *
   * @param {object} [parameters.subscriptionKeyParameterNames] Protocols over
   * which API is made available.
   *
   * @param {string} [parameters.subscriptionKeyParameterNames.header]
   * Subscription key header name.
   *
   * @param {string} [parameters.subscriptionKeyParameterNames.query]
   * Subscription key query string parameter name.
   *
   * @param {string} [parameters.apiType] Type of API. Possible values include:
   * 'http', 'soap'
   *
   * @param {string} [parameters.apiRevision] Describes the Revision of the Api.
   * If no value is provided, default revision 1 is created
   *
   * @param {string} [parameters.apiVersion] Indicates the Version identifier of
   * the API if the API is versioned
   *
   * @param {string} [parameters.apiVersionSetId] A resource identifier for the
   * related ApiVersionSet.
   *
   * @param {string} [parameters.displayName] API name.
   *
   * @param {string} [parameters.serviceUrl] Absolute URL of the backend service
   * implementing this API.
   *
   * @param {string} [parameters.path] Relative URL uniquely identifying this API
   * and all of its resource paths within the API Management service instance. It
   * is appended to the API endpoint base URL specified during the service
   * instance creation to form a public URL for this API.
   *
   * @param {array} [parameters.protocols] Describes on which protocols the
   * operations in this API can be invoked.
   *
   * @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.
   */
  update(resourceGroupName, serviceName, apiId, 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, apiId, parameters, ifMatch, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._update(resourceGroupName, serviceName, apiId, parameters, ifMatch, options, optionalCallback);
    }
  }

  /**
   * Deletes the specified API 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} apiId API revision identifier. Must be unique in the current
   * API Management service instance. Non-current revision has ;rev=n as a suffix
   * where n is the revision number.
   *
   * @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.deleteRevisions] Delete all revisions of the Api.
   *
   * @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, apiId, ifMatch, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._deleteMethod(resourceGroupName, serviceName, apiId, 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 API 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} apiId API revision identifier. Must be unique in the current
   * API Management service instance. Non-current revision has ;rev=n as a suffix
   * where n is the revision number.
   *
   * @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.deleteRevisions] Delete all revisions of the Api.
   *
   * @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, apiId, 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, apiId, ifMatch, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._deleteMethod(resourceGroupName, serviceName, apiId, ifMatch, options, optionalCallback);
    }
  }

  /**
   * Lists a collection of apis associated with tags.
   *
   * @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       | Supported operators    |
   * Supported functions                         |
   * |-------------|------------------------|---------------------------------------------|
   * | id          | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
   * endswith |
   * | name        | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
   * endswith |
   * | aid         | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
   * endswith |
   * | apiRevision | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
   * endswith |
   * | path        | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
   * endswith |
   * | description | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
   * endswith |
   * | serviceUrl  | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
   * endswith |
   * | isCurrent   | eq                     | substringof, contains, startswith,
   * endswith |
   *
   * @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<TagResourceCollection>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  listByTagsWithHttpOperationResponse(resourceGroupName, serviceName, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._listByTags(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 a collection of apis associated with tags.
   *
   * @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       | Supported operators    |
   * Supported functions                         |
   * |-------------|------------------------|---------------------------------------------|
   * | id          | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
   * endswith |
   * | name        | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
   * endswith |
   * | aid         | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
   * endswith |
   * | apiRevision | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
   * endswith |
   * | path        | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
   * endswith |
   * | description | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
   * endswith |
   * | serviceUrl  | ge, le, eq, ne, gt, lt | substringof, contains, startswith,
   * endswith |
   * | isCurrent   | eq                     | substringof, contains, startswith,
   * endswith |
   *
   * @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 {TagResourceCollection} - 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 TagResourceCollection} 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.
   */
  listByTags(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._listByTags(resourceGroupName, serviceName, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._listByTags(resourceGroupName, serviceName, options, optionalCallback);
    }
  }

  /**
   * Lists all APIs 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<ApiCollection>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  listByServiceNextWithHttpOperationResponse(nextPageLink, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._listByServiceNext(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 APIs 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 {ApiCollection} - 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 ApiCollection} 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.
   */
  listByServiceNext(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._listByServiceNext(nextPageLink, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._listByServiceNext(nextPageLink, options, optionalCallback);
    }
  }

  /**
   * Lists a collection of apis associated with tags.
   *
   * @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<TagResourceCollection>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  listByTagsNextWithHttpOperationResponse(nextPageLink, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._listByTagsNext(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 a collection of apis associated with tags.
   *
   * @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 {TagResourceCollection} - 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 TagResourceCollection} 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.
   */
  listByTagsNext(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._listByTagsNext(nextPageLink, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._listByTagsNext(nextPageLink, options, optionalCallback);
    }
  }

}

module.exports = Api;
