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

/* jshint latedef:false */
/* jshint forin:false */
/* jshint noempty:false */

'use strict';

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

const models = require('./models');


/**
 * @summary The API returns the detected language and a numeric score between 0
 * and 1.
 *
 * Scores close to 1 indicate 100% certainty that the identified language is
 * true. A total of 120 languages are supported.
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {boolean} [options.showStats] (optional) if set to true, response
 * will contain input and document level statistics.
 *
 * @param {object} [options.languageBatchInput] Collection of documents to
 * analyze.
 *
 * @param {array} [options.languageBatchInput.documents]
 *
 * @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 LanguageBatchResult} 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 _detectLanguage(options, callback) {
   /* jshint validthis: true */
  let client = this;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }
  let showStats = (options && options.showStats !== undefined) ? options.showStats : undefined;
  let languageBatchInput = (options && options.languageBatchInput !== undefined) ? options.languageBatchInput : undefined;
  // Validate
  try {
    if (this.endpoint === null || this.endpoint === undefined || typeof this.endpoint.valueOf() !== 'string') {
      throw new Error('this.endpoint cannot be null or undefined and it must be of type string.');
    }
    if (showStats !== null && showStats !== undefined && typeof showStats !== 'boolean') {
      throw new Error('showStats must be of type boolean.');
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  let baseUrl = this.baseUri;
  let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'languages';
  requestUrl = requestUrl.replace('{Endpoint}', this.endpoint);
  let queryParameters = [];
  if (showStats !== null && showStats !== undefined) {
    queryParameters.push('showStats=' + encodeURIComponent(showStats.toString()));
  }
  if (queryParameters.length > 0) {
    requestUrl += '?' + queryParameters.join('&');
  }

  // Create HTTP transport objects
  let httpRequest = new WebResource();
  httpRequest.method = 'POST';
  httpRequest.url = requestUrl;
  httpRequest.headers = {};
  // Set Headers
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  if(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 (languageBatchInput !== null && languageBatchInput !== undefined) {
      let requestModelMapper = new client.models['LanguageBatchInput']().mapper();
      requestModel = client.serialize(requestModelMapper, languageBatchInput, 'languageBatchInput');
      requestContent = JSON.stringify(requestModel);
    }
  } catch (error) {
    let serializationError = new Error(`Error "${error.message}" occurred in serializing the ` +
        `payload - ${JSON.stringify(languageBatchInput, null, 2)}.`);
    return callback(serializationError);
  }
  httpRequest.body = requestContent;
  // Send Request
  return client.pipeline(httpRequest, (err, response, responseBody) => {
    if (err) {
      return callback(err);
    }
    let statusCode = response.statusCode;
    if (statusCode !== 200) {
      let error = new Error(responseBody);
      error.statusCode = response.statusCode;
      error.request = msRest.stripRequest(httpRequest);
      error.response = msRest.stripResponse(response);
      if (responseBody === '') responseBody = null;
      let parsedErrorResponse;
      try {
        parsedErrorResponse = JSON.parse(responseBody);
        if (parsedErrorResponse) {
          let internalError = null;
          if (parsedErrorResponse.error) internalError = parsedErrorResponse.error;
          error.code = internalError ? internalError.code : parsedErrorResponse.code;
          error.message = internalError ? internalError.message : parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          let resultMapper = new client.models['ErrorResponse']().mapper();
          error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
        }
      } catch (defaultError) {
        error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
                         `- "${responseBody}" for the default response.`;
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    let result = null;
    if (responseBody === '') responseBody = null;
    // Deserialize Response
    if (statusCode === 200) {
      let parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          let resultMapper = new client.models['LanguageBatchResult']().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);
  });
}

/**
 * @summary The API returns a list of recognized entities in a given document.
 *
 * To get even more information on each recognized entity we recommend using
 * the Bing Entity Search API by querying for the recognized entities names.
 * See the <a
 * href="https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/text-analytics-supported-languages">Supported
 * languages in Text Analytics API</a> for the list of enabled languages.
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {boolean} [options.showStats] (optional) if set to true, response
 * will contain input and document level statistics.
 *
 * @param {object} [options.multiLanguageBatchInput] Collection of documents to
 * analyze.
 *
 * @param {array} [options.multiLanguageBatchInput.documents]
 *
 * @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 EntitiesBatchResult} 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 _entities(options, callback) {
   /* jshint validthis: true */
  let client = this;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }
  let showStats = (options && options.showStats !== undefined) ? options.showStats : undefined;
  let multiLanguageBatchInput = (options && options.multiLanguageBatchInput !== undefined) ? options.multiLanguageBatchInput : undefined;
  // Validate
  try {
    if (this.endpoint === null || this.endpoint === undefined || typeof this.endpoint.valueOf() !== 'string') {
      throw new Error('this.endpoint cannot be null or undefined and it must be of type string.');
    }
    if (showStats !== null && showStats !== undefined && typeof showStats !== 'boolean') {
      throw new Error('showStats must be of type boolean.');
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  let baseUrl = this.baseUri;
  let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'entities';
  requestUrl = requestUrl.replace('{Endpoint}', this.endpoint);
  let queryParameters = [];
  if (showStats !== null && showStats !== undefined) {
    queryParameters.push('showStats=' + encodeURIComponent(showStats.toString()));
  }
  if (queryParameters.length > 0) {
    requestUrl += '?' + queryParameters.join('&');
  }

  // Create HTTP transport objects
  let httpRequest = new WebResource();
  httpRequest.method = 'POST';
  httpRequest.url = requestUrl;
  httpRequest.headers = {};
  // Set Headers
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  if(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 (multiLanguageBatchInput !== null && multiLanguageBatchInput !== undefined) {
      let requestModelMapper = new client.models['MultiLanguageBatchInput']().mapper();
      requestModel = client.serialize(requestModelMapper, multiLanguageBatchInput, 'multiLanguageBatchInput');
      requestContent = JSON.stringify(requestModel);
    }
  } catch (error) {
    let serializationError = new Error(`Error "${error.message}" occurred in serializing the ` +
        `payload - ${JSON.stringify(multiLanguageBatchInput, null, 2)}.`);
    return callback(serializationError);
  }
  httpRequest.body = requestContent;
  // Send Request
  return client.pipeline(httpRequest, (err, response, responseBody) => {
    if (err) {
      return callback(err);
    }
    let statusCode = response.statusCode;
    if (statusCode !== 200) {
      let error = new Error(responseBody);
      error.statusCode = response.statusCode;
      error.request = msRest.stripRequest(httpRequest);
      error.response = msRest.stripResponse(response);
      if (responseBody === '') responseBody = null;
      let parsedErrorResponse;
      try {
        parsedErrorResponse = JSON.parse(responseBody);
        if (parsedErrorResponse) {
          let internalError = null;
          if (parsedErrorResponse.error) internalError = parsedErrorResponse.error;
          error.code = internalError ? internalError.code : parsedErrorResponse.code;
          error.message = internalError ? internalError.message : parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          let resultMapper = new client.models['ErrorResponse']().mapper();
          error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
        }
      } catch (defaultError) {
        error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
                         `- "${responseBody}" for the default response.`;
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    let result = null;
    if (responseBody === '') responseBody = null;
    // Deserialize Response
    if (statusCode === 200) {
      let parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          let resultMapper = new client.models['EntitiesBatchResult']().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);
  });
}

/**
 * @summary The API returns a list of strings denoting the key talking points
 * in the input text.
 *
 * See the <a
 * href="https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/overview#supported-languages">Text
 * Analytics Documentation</a> for details about the languages that are
 * supported by key phrase extraction.
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {boolean} [options.showStats] (optional) if set to true, response
 * will contain input and document level statistics.
 *
 * @param {object} [options.multiLanguageBatchInput] Collection of documents to
 * analyze. Documents can now contain a language field to indicate the text
 * language
 *
 * @param {array} [options.multiLanguageBatchInput.documents]
 *
 * @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 KeyPhraseBatchResult} 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 _keyPhrases(options, callback) {
   /* jshint validthis: true */
  let client = this;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }
  let showStats = (options && options.showStats !== undefined) ? options.showStats : undefined;
  let multiLanguageBatchInput = (options && options.multiLanguageBatchInput !== undefined) ? options.multiLanguageBatchInput : undefined;
  // Validate
  try {
    if (this.endpoint === null || this.endpoint === undefined || typeof this.endpoint.valueOf() !== 'string') {
      throw new Error('this.endpoint cannot be null or undefined and it must be of type string.');
    }
    if (showStats !== null && showStats !== undefined && typeof showStats !== 'boolean') {
      throw new Error('showStats must be of type boolean.');
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  let baseUrl = this.baseUri;
  let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'keyPhrases';
  requestUrl = requestUrl.replace('{Endpoint}', this.endpoint);
  let queryParameters = [];
  if (showStats !== null && showStats !== undefined) {
    queryParameters.push('showStats=' + encodeURIComponent(showStats.toString()));
  }
  if (queryParameters.length > 0) {
    requestUrl += '?' + queryParameters.join('&');
  }

  // Create HTTP transport objects
  let httpRequest = new WebResource();
  httpRequest.method = 'POST';
  httpRequest.url = requestUrl;
  httpRequest.headers = {};
  // Set Headers
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  if(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 (multiLanguageBatchInput !== null && multiLanguageBatchInput !== undefined) {
      let requestModelMapper = new client.models['MultiLanguageBatchInput']().mapper();
      requestModel = client.serialize(requestModelMapper, multiLanguageBatchInput, 'multiLanguageBatchInput');
      requestContent = JSON.stringify(requestModel);
    }
  } catch (error) {
    let serializationError = new Error(`Error "${error.message}" occurred in serializing the ` +
        `payload - ${JSON.stringify(multiLanguageBatchInput, null, 2)}.`);
    return callback(serializationError);
  }
  httpRequest.body = requestContent;
  // Send Request
  return client.pipeline(httpRequest, (err, response, responseBody) => {
    if (err) {
      return callback(err);
    }
    let statusCode = response.statusCode;
    if (statusCode !== 200) {
      let error = new Error(responseBody);
      error.statusCode = response.statusCode;
      error.request = msRest.stripRequest(httpRequest);
      error.response = msRest.stripResponse(response);
      if (responseBody === '') responseBody = null;
      let parsedErrorResponse;
      try {
        parsedErrorResponse = JSON.parse(responseBody);
        if (parsedErrorResponse) {
          let internalError = null;
          if (parsedErrorResponse.error) internalError = parsedErrorResponse.error;
          error.code = internalError ? internalError.code : parsedErrorResponse.code;
          error.message = internalError ? internalError.message : parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          let resultMapper = new client.models['ErrorResponse']().mapper();
          error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
        }
      } catch (defaultError) {
        error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
                         `- "${responseBody}" for the default response.`;
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    let result = null;
    if (responseBody === '') responseBody = null;
    // Deserialize Response
    if (statusCode === 200) {
      let parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          let resultMapper = new client.models['KeyPhraseBatchResult']().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);
  });
}

/**
 * @summary The API returns a numeric score between 0 and 1.
 *
 * Scores close to 1 indicate positive sentiment, while scores close to 0
 * indicate negative sentiment. A score of 0.5 indicates the lack of sentiment
 * (e.g. a factoid statement). See the <a
 * href="https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/overview#supported-languages">Text
 * Analytics Documentation</a> for details about the languages that are
 * supported by sentiment analysis.
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {boolean} [options.showStats] (optional) if set to true, response
 * will contain input and document level statistics.
 *
 * @param {object} [options.multiLanguageBatchInput] Collection of documents to
 * analyze.
 *
 * @param {array} [options.multiLanguageBatchInput.documents]
 *
 * @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.
 *
 *                      {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 _sentiment(options, callback) {
   /* jshint validthis: true */
  let client = this;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }
  let showStats = (options && options.showStats !== undefined) ? options.showStats : undefined;
  let multiLanguageBatchInput = (options && options.multiLanguageBatchInput !== undefined) ? options.multiLanguageBatchInput : undefined;
  // Validate
  try {
    if (this.endpoint === null || this.endpoint === undefined || typeof this.endpoint.valueOf() !== 'string') {
      throw new Error('this.endpoint cannot be null or undefined and it must be of type string.');
    }
    if (showStats !== null && showStats !== undefined && typeof showStats !== 'boolean') {
      throw new Error('showStats must be of type boolean.');
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  let baseUrl = this.baseUri;
  let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'sentiment';
  requestUrl = requestUrl.replace('{Endpoint}', this.endpoint);
  let queryParameters = [];
  if (showStats !== null && showStats !== undefined) {
    queryParameters.push('showStats=' + encodeURIComponent(showStats.toString()));
  }
  if (queryParameters.length > 0) {
    requestUrl += '?' + queryParameters.join('&');
  }

  // Create HTTP transport objects
  let httpRequest = new WebResource();
  httpRequest.method = 'POST';
  httpRequest.url = requestUrl;
  httpRequest.headers = {};
  // Set Headers
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  if(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 (multiLanguageBatchInput !== null && multiLanguageBatchInput !== undefined) {
      let requestModelMapper = new client.models['MultiLanguageBatchInput']().mapper();
      requestModel = client.serialize(requestModelMapper, multiLanguageBatchInput, 'multiLanguageBatchInput');
      requestContent = JSON.stringify(requestModel);
    }
  } catch (error) {
    let serializationError = new Error(`Error "${error.message}" occurred in serializing the ` +
        `payload - ${JSON.stringify(multiLanguageBatchInput, 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 !== 500) {
      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;
        }
      } 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['SentimentBatchResult']().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 === 500) {
      let parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          let resultMapper = new client.models['ErrorResponse']().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);
  });
}

/** Class representing a TextAnalyticsClient. */
class TextAnalyticsClient extends ServiceClient {
  /**
   * Create a TextAnalyticsClient.
   * @param {credentials} credentials - Subscription credentials which uniquely identify client subscription.
   * @param {string} endpoint - Supported Cognitive Services endpoints (protocol and hostname, for example: https://westus.api.cognitive.microsoft.com).
   * @param {object} [options] - The parameter options
   * @param {Array} [options.filters] - Filters to be added to the request pipeline
   * @param {object} [options.requestOptions] - Options for the underlying request object
   * {@link https://github.com/request/request#requestoptions-callback Options doc}
   * @param {boolean} [options.noRetryPolicy] - If set to true, turn off default retry policy
   */
  constructor(credentials, endpoint, options) {
    if (credentials === null || credentials === undefined) {
      throw new Error('\'credentials\' cannot be null.');
    }
    if (endpoint === null || endpoint === undefined) {
      throw new Error('\'endpoint\' cannot be null.');
    }

    if (!options) options = {};

    super(credentials, options);

    this.baseUri = '{Endpoint}/text/analytics/v2.1';
    this.credentials = credentials;
    this.endpoint = endpoint;

    let packageInfo = this.getPackageJsonInfo(__dirname);
    this.addUserAgentInfo(`${packageInfo.name}/${packageInfo.version}`);
    this.models = models;
    this._detectLanguage = _detectLanguage;
    this._entities = _entities;
    this._keyPhrases = _keyPhrases;
    this._sentiment = _sentiment;
    msRest.addSerializationMixin(this);
  }

  /**
   * @summary The API returns the detected language and a numeric score between 0
   * and 1.
   *
   * Scores close to 1 indicate 100% certainty that the identified language is
   * true. A total of 120 languages are supported.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {boolean} [options.showStats] (optional) if set to true, response
   * will contain input and document level statistics.
   *
   * @param {object} [options.languageBatchInput] Collection of documents to
   * analyze.
   *
   * @param {array} [options.languageBatchInput.documents]
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<LanguageBatchResult>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  detectLanguageWithHttpOperationResponse(options) {
    let client = this;
    let self = this;
    return new Promise((resolve, reject) => {
      self._detectLanguage(options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * @summary The API returns the detected language and a numeric score between 0
   * and 1.
   *
   * Scores close to 1 indicate 100% certainty that the identified language is
   * true. A total of 120 languages are supported.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {boolean} [options.showStats] (optional) if set to true, response
   * will contain input and document level statistics.
   *
   * @param {object} [options.languageBatchInput] Collection of documents to
   * analyze.
   *
   * @param {array} [options.languageBatchInput.documents]
   *
   * @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 {LanguageBatchResult} - 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 LanguageBatchResult} 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.
   */
  detectLanguage(options, optionalCallback) {
    let client = this;
    let self = this;
    if (!optionalCallback && typeof options === 'function') {
      optionalCallback = options;
      options = null;
    }
    if (!optionalCallback) {
      return new Promise((resolve, reject) => {
        self._detectLanguage(options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._detectLanguage(options, optionalCallback);
    }
  }

  /**
   * @summary The API returns a list of recognized entities in a given document.
   *
   * To get even more information on each recognized entity we recommend using
   * the Bing Entity Search API by querying for the recognized entities names.
   * See the <a
   * href="https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/text-analytics-supported-languages">Supported
   * languages in Text Analytics API</a> for the list of enabled languages.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {boolean} [options.showStats] (optional) if set to true, response
   * will contain input and document level statistics.
   *
   * @param {object} [options.multiLanguageBatchInput] Collection of documents to
   * analyze.
   *
   * @param {array} [options.multiLanguageBatchInput.documents]
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<EntitiesBatchResult>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  entitiesWithHttpOperationResponse(options) {
    let client = this;
    let self = this;
    return new Promise((resolve, reject) => {
      self._entities(options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * @summary The API returns a list of recognized entities in a given document.
   *
   * To get even more information on each recognized entity we recommend using
   * the Bing Entity Search API by querying for the recognized entities names.
   * See the <a
   * href="https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/text-analytics-supported-languages">Supported
   * languages in Text Analytics API</a> for the list of enabled languages.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {boolean} [options.showStats] (optional) if set to true, response
   * will contain input and document level statistics.
   *
   * @param {object} [options.multiLanguageBatchInput] Collection of documents to
   * analyze.
   *
   * @param {array} [options.multiLanguageBatchInput.documents]
   *
   * @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 {EntitiesBatchResult} - 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 EntitiesBatchResult} 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.
   */
  entities(options, optionalCallback) {
    let client = this;
    let self = this;
    if (!optionalCallback && typeof options === 'function') {
      optionalCallback = options;
      options = null;
    }
    if (!optionalCallback) {
      return new Promise((resolve, reject) => {
        self._entities(options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._entities(options, optionalCallback);
    }
  }

  /**
   * @summary The API returns a list of strings denoting the key talking points
   * in the input text.
   *
   * See the <a
   * href="https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/overview#supported-languages">Text
   * Analytics Documentation</a> for details about the languages that are
   * supported by key phrase extraction.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {boolean} [options.showStats] (optional) if set to true, response
   * will contain input and document level statistics.
   *
   * @param {object} [options.multiLanguageBatchInput] Collection of documents to
   * analyze. Documents can now contain a language field to indicate the text
   * language
   *
   * @param {array} [options.multiLanguageBatchInput.documents]
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<KeyPhraseBatchResult>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  keyPhrasesWithHttpOperationResponse(options) {
    let client = this;
    let self = this;
    return new Promise((resolve, reject) => {
      self._keyPhrases(options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * @summary The API returns a list of strings denoting the key talking points
   * in the input text.
   *
   * See the <a
   * href="https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/overview#supported-languages">Text
   * Analytics Documentation</a> for details about the languages that are
   * supported by key phrase extraction.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {boolean} [options.showStats] (optional) if set to true, response
   * will contain input and document level statistics.
   *
   * @param {object} [options.multiLanguageBatchInput] Collection of documents to
   * analyze. Documents can now contain a language field to indicate the text
   * language
   *
   * @param {array} [options.multiLanguageBatchInput.documents]
   *
   * @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 {KeyPhraseBatchResult} - 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 KeyPhraseBatchResult} 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.
   */
  keyPhrases(options, optionalCallback) {
    let client = this;
    let self = this;
    if (!optionalCallback && typeof options === 'function') {
      optionalCallback = options;
      options = null;
    }
    if (!optionalCallback) {
      return new Promise((resolve, reject) => {
        self._keyPhrases(options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._keyPhrases(options, optionalCallback);
    }
  }

  /**
   * @summary The API returns a numeric score between 0 and 1.
   *
   * Scores close to 1 indicate positive sentiment, while scores close to 0
   * indicate negative sentiment. A score of 0.5 indicates the lack of sentiment
   * (e.g. a factoid statement). See the <a
   * href="https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/overview#supported-languages">Text
   * Analytics Documentation</a> for details about the languages that are
   * supported by sentiment analysis.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {boolean} [options.showStats] (optional) if set to true, response
   * will contain input and document level statistics.
   *
   * @param {object} [options.multiLanguageBatchInput] Collection of documents to
   * analyze.
   *
   * @param {array} [options.multiLanguageBatchInput.documents]
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<Object>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  sentimentWithHttpOperationResponse(options) {
    let client = this;
    let self = this;
    return new Promise((resolve, reject) => {
      self._sentiment(options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * @summary The API returns a numeric score between 0 and 1.
   *
   * Scores close to 1 indicate positive sentiment, while scores close to 0
   * indicate negative sentiment. A score of 0.5 indicates the lack of sentiment
   * (e.g. a factoid statement). See the <a
   * href="https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/overview#supported-languages">Text
   * Analytics Documentation</a> for details about the languages that are
   * supported by sentiment analysis.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {boolean} [options.showStats] (optional) if set to true, response
   * will contain input and document level statistics.
   *
   * @param {object} [options.multiLanguageBatchInput] Collection of documents to
   * analyze.
   *
   * @param {array} [options.multiLanguageBatchInput.documents]
   *
   * @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 {Object} - 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.
   *
   *                      {object} [request]  - The HTTP Request object if an error did not occur.
   *
   *                      {stream} [response] - The HTTP Response stream if an error did not occur.
   */
  sentiment(options, optionalCallback) {
    let client = this;
    let self = this;
    if (!optionalCallback && typeof options === 'function') {
      optionalCallback = options;
      options = null;
    }
    if (!optionalCallback) {
      return new Promise((resolve, reject) => {
        self._sentiment(options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._sentiment(options, optionalCallback);
    }
  }

}

module.exports = TextAnalyticsClient;
module.exports['default'] = TextAnalyticsClient;
module.exports.TextAnalyticsClient = TextAnalyticsClient;
module.exports.TextAnalyticsModels = models;
