/*
 * 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 WebResource = msRest.WebResource;

/**
 * @summary Gets a list of crash groups and whether the list contains all
 * available groups.
 *
 * Gets a list of crash groups and whether the list contains all available
 * groups.
 *
 * @param {string} appName The name of the application
 *
 * @param {string} ownerName The name of the owner
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {string} [options.orderby] the OData-like $orderby argument. Possible
 * values include: 'last_occurrence asc', 'last_occurrence desc', 'count asc',
 * 'count desc', 'display_id asc', 'display_id desc', 'impacted_users asc',
 * 'impacted_users desc'
 *
 * @param {string} [options.appVersion] version
 *
 * @param {string} [options.continuationToken] Cassandra request continuation
 * token. The token is used for pagination.
 *
 * @param {string} [options.groupStatus] Possible values include: 'open',
 * 'closed', 'ignored'
 *
 * @param {string} [options.groupTextSearch] A freetext search that matches in
 * crash, crash types, crash stack_traces and crash user
 *
 * @param {string} [options.groupType] Possible values include: 'GroupType1',
 * 'GroupType2'
 *
 * @param {boolean} [options.includeUserCounts] if true include impacted user
 * counts in crash group results
 *
 * @param {date} [options.lastOccurrenceFrom] Earliest date when the last time
 * a crash occured in a crash group
 *
 * @param {date} [options.lastOccurrenceTo] Latest date when the last time a
 * crash occured in a crash group
 *
 * @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 CrashGroupsContainer} for more information.
 *
 *                      {object} [request]  - The HTTP Request object if an error did not occur.
 *
 *                      {stream} [response] - The HTTP Response stream if an error did not occur.
 */
function _list(appName, ownerName, 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 orderby = (options && options.orderby !== undefined) ? options.orderby : 'last_occurrence desc';
  let appVersion = (options && options.appVersion !== undefined) ? options.appVersion : undefined;
  let continuationToken = (options && options.continuationToken !== undefined) ? options.continuationToken : undefined;
  let groupStatus = (options && options.groupStatus !== undefined) ? options.groupStatus : undefined;
  let groupTextSearch = (options && options.groupTextSearch !== undefined) ? options.groupTextSearch : undefined;
  let groupType = (options && options.groupType !== undefined) ? options.groupType : undefined;
  let includeUserCounts = (options && options.includeUserCounts !== undefined) ? options.includeUserCounts : false;
  let lastOccurrenceFrom = (options && options.lastOccurrenceFrom !== undefined) ? options.lastOccurrenceFrom : undefined;
  let lastOccurrenceTo = (options && options.lastOccurrenceTo !== undefined) ? options.lastOccurrenceTo : undefined;
  // Validate
  try {
    if (orderby !== null && orderby !== undefined && typeof orderby.valueOf() !== 'string') {
      throw new Error('orderby must be of type string.');
    }
    if (appName === null || appName === undefined || typeof appName.valueOf() !== 'string') {
      throw new Error('appName cannot be null or undefined and it must be of type string.');
    }
    if (appVersion !== null && appVersion !== undefined && typeof appVersion.valueOf() !== 'string') {
      throw new Error('appVersion must be of type string.');
    }
    if (continuationToken !== null && continuationToken !== undefined && typeof continuationToken.valueOf() !== 'string') {
      throw new Error('continuationToken must be of type string.');
    }
    if (groupStatus !== null && groupStatus !== undefined && typeof groupStatus.valueOf() !== 'string') {
      throw new Error('groupStatus must be of type string.');
    }
    if (groupTextSearch !== null && groupTextSearch !== undefined && typeof groupTextSearch.valueOf() !== 'string') {
      throw new Error('groupTextSearch must be of type string.');
    }
    if (groupType !== null && groupType !== undefined && typeof groupType.valueOf() !== 'string') {
      throw new Error('groupType must be of type string.');
    }
    if (includeUserCounts !== null && includeUserCounts !== undefined && typeof includeUserCounts !== 'boolean') {
      throw new Error('includeUserCounts must be of type boolean.');
    }
    if (lastOccurrenceFrom && !(lastOccurrenceFrom instanceof Date ||
        (typeof lastOccurrenceFrom.valueOf() === 'string' && !isNaN(Date.parse(lastOccurrenceFrom))))) {
          throw new Error('lastOccurrenceFrom must be of type date.');
        }
    if (lastOccurrenceTo && !(lastOccurrenceTo instanceof Date ||
        (typeof lastOccurrenceTo.valueOf() === 'string' && !isNaN(Date.parse(lastOccurrenceTo))))) {
          throw new Error('lastOccurrenceTo must be of type date.');
        }
    if (ownerName === null || ownerName === undefined || typeof ownerName.valueOf() !== 'string') {
      throw new Error('ownerName cannot be null or undefined and it must be of type string.');
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  let baseUrl = this.client.baseUri;
  let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'v0.1/apps/{owner_name}/{app_name}/crash_groups';
  requestUrl = requestUrl.replace('{app_name}', encodeURIComponent(appName));
  requestUrl = requestUrl.replace('{owner_name}', encodeURIComponent(ownerName));
  let queryParameters = [];
  if (orderby !== null && orderby !== undefined) {
    queryParameters.push('$orderby=' + encodeURIComponent(orderby));
  }
  if (appVersion !== null && appVersion !== undefined) {
    queryParameters.push('app_version=' + encodeURIComponent(appVersion));
  }
  if (continuationToken !== null && continuationToken !== undefined) {
    queryParameters.push('continuation_token=' + encodeURIComponent(continuationToken));
  }
  if (groupStatus !== null && groupStatus !== undefined) {
    queryParameters.push('group_status=' + encodeURIComponent(groupStatus));
  }
  if (groupTextSearch !== null && groupTextSearch !== undefined) {
    queryParameters.push('group_text_search=' + encodeURIComponent(groupTextSearch));
  }
  if (groupType !== null && groupType !== undefined) {
    queryParameters.push('group_type=' + encodeURIComponent(groupType));
  }
  if (includeUserCounts !== null && includeUserCounts !== undefined) {
    queryParameters.push('include_user_counts=' + encodeURIComponent(includeUserCounts.toString()));
  }
  if (lastOccurrenceFrom !== null && lastOccurrenceFrom !== undefined) {
    queryParameters.push('last_occurrence_from=' + encodeURIComponent(client.serializeObject(lastOccurrenceFrom)));
  }
  if (lastOccurrenceTo !== null && lastOccurrenceTo !== undefined) {
    queryParameters.push('last_occurrence_to=' + encodeURIComponent(client.serializeObject(lastOccurrenceTo)));
  }
  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(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;
        }
      } 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['CrashGroupsContainer']().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 a specific group
 *
 * @param {string} appName The name of the application
 *
 * @param {string} crashGroupId id of a specific group
 *
 * @param {string} ownerName The name of the owner
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {boolean} [options.includeUserCounts] if true include impacted user
 * counts in crash group results
 *
 * @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 CrashGroup} 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(appName, crashGroupId, ownerName, 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 includeUserCounts = (options && options.includeUserCounts !== undefined) ? options.includeUserCounts : false;
  // Validate
  try {
    if (appName === null || appName === undefined || typeof appName.valueOf() !== 'string') {
      throw new Error('appName cannot be null or undefined and it must be of type string.');
    }
    if (crashGroupId === null || crashGroupId === undefined || typeof crashGroupId.valueOf() !== 'string') {
      throw new Error('crashGroupId cannot be null or undefined and it must be of type string.');
    }
    if (includeUserCounts !== null && includeUserCounts !== undefined && typeof includeUserCounts !== 'boolean') {
      throw new Error('includeUserCounts must be of type boolean.');
    }
    if (ownerName === null || ownerName === undefined || typeof ownerName.valueOf() !== 'string') {
      throw new Error('ownerName cannot be null or undefined and it must be of type string.');
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  let baseUrl = this.client.baseUri;
  let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'v0.1/apps/{owner_name}/{app_name}/crash_groups/{crash_group_id}';
  requestUrl = requestUrl.replace('{app_name}', encodeURIComponent(appName));
  requestUrl = requestUrl.replace('{crash_group_id}', encodeURIComponent(crashGroupId));
  requestUrl = requestUrl.replace('{owner_name}', encodeURIComponent(ownerName));
  let queryParameters = [];
  if (includeUserCounts !== null && includeUserCounts !== undefined) {
    queryParameters.push('include_user_counts=' + encodeURIComponent(includeUserCounts.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(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;
        }
      } 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['CrashGroup']().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);
  });
}

/**
 * Updates a group
 *
 * @param {string} appName The name of the application
 *
 * @param {string} crashGroupId id of a specific group
 *
 * @param {object} group Group change object. All fields are optional and only
 * provided fields will get updated.
 *
 * @param {object} [group.status]
 *
 * @param {string} [group.annotation]
 *
 * @param {string} ownerName The name of the owner
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {boolean} [options.includeUserCounts] if true include impacted user
 * counts in crash group results
 *
 * @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 CrashGroup} 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 _update(appName, crashGroupId, group, ownerName, 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 includeUserCounts = (options && options.includeUserCounts !== undefined) ? options.includeUserCounts : false;
  // Validate
  try {
    if (appName === null || appName === undefined || typeof appName.valueOf() !== 'string') {
      throw new Error('appName cannot be null or undefined and it must be of type string.');
    }
    if (crashGroupId === null || crashGroupId === undefined || typeof crashGroupId.valueOf() !== 'string') {
      throw new Error('crashGroupId cannot be null or undefined and it must be of type string.');
    }
    if (group === null || group === undefined) {
      throw new Error('group cannot be null or undefined.');
    }
    if (includeUserCounts !== null && includeUserCounts !== undefined && typeof includeUserCounts !== 'boolean') {
      throw new Error('includeUserCounts must be of type boolean.');
    }
    if (ownerName === null || ownerName === undefined || typeof ownerName.valueOf() !== 'string') {
      throw new Error('ownerName cannot be null or undefined and it must be of type string.');
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  let baseUrl = this.client.baseUri;
  let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'v0.1/apps/{owner_name}/{app_name}/crash_groups/{crash_group_id}';
  requestUrl = requestUrl.replace('{app_name}', encodeURIComponent(appName));
  requestUrl = requestUrl.replace('{crash_group_id}', encodeURIComponent(crashGroupId));
  requestUrl = requestUrl.replace('{owner_name}', encodeURIComponent(ownerName));
  let queryParameters = [];
  if (includeUserCounts !== null && includeUserCounts !== undefined) {
    queryParameters.push('include_user_counts=' + encodeURIComponent(includeUserCounts.toString()));
  }
  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(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 (group !== null && group !== undefined) {
      let requestModelMapper = new client.models['CrashGroupChange']().mapper();
      requestModel = client.serialize(requestModelMapper, group, 'group');
      requestContent = JSON.stringify(requestModel);
    }
  } catch (error) {
    let serializationError = new Error(`Error "${error.message}" occurred in serializing the ` +
        `payload - ${JSON.stringify(group, 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;
        }
      } 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['CrashGroup']().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 a stacktrace for a specific crash
 *
 * @param {string} appName The name of the application
 *
 * @param {string} crashGroupId id of a specific group
 *
 * @param {string} ownerName The name of the owner
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {boolean} [options.groupingOnly] true if the stacktrace should be
 * only the relevant thread / exception. Default is false
 *
 * @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 Stacktrace} 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 _getStacktrace(appName, crashGroupId, ownerName, 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 groupingOnly = (options && options.groupingOnly !== undefined) ? options.groupingOnly : false;
  // Validate
  try {
    if (appName === null || appName === undefined || typeof appName.valueOf() !== 'string') {
      throw new Error('appName cannot be null or undefined and it must be of type string.');
    }
    if (crashGroupId === null || crashGroupId === undefined || typeof crashGroupId.valueOf() !== 'string') {
      throw new Error('crashGroupId cannot be null or undefined and it must be of type string.');
    }
    if (groupingOnly !== null && groupingOnly !== undefined && typeof groupingOnly !== 'boolean') {
      throw new Error('groupingOnly must be of type boolean.');
    }
    if (ownerName === null || ownerName === undefined || typeof ownerName.valueOf() !== 'string') {
      throw new Error('ownerName cannot be null or undefined and it must be of type string.');
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  let baseUrl = this.client.baseUri;
  let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'v0.1/apps/{owner_name}/{app_name}/crash_groups/{crash_group_id}/stacktrace';
  requestUrl = requestUrl.replace('{app_name}', encodeURIComponent(appName));
  requestUrl = requestUrl.replace('{crash_group_id}', encodeURIComponent(crashGroupId));
  requestUrl = requestUrl.replace('{owner_name}', encodeURIComponent(ownerName));
  let queryParameters = [];
  if (groupingOnly !== null && groupingOnly !== undefined) {
    queryParameters.push('grouping_only=' + encodeURIComponent(groupingOnly.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(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;
        }
      } 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['Stacktrace']().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 CrashGroups. */
class CrashGroups {
  /**
   * Create a CrashGroups.
   * @param {CrashClient} client Reference to the service client.
   */
  constructor(client) {
    this.client = client;
    this._list = _list;
    this._get = _get;
    this._update = _update;
    this._getStacktrace = _getStacktrace;
  }

  /**
   * @summary Gets a list of crash groups and whether the list contains all
   * available groups.
   *
   * Gets a list of crash groups and whether the list contains all available
   * groups.
   *
   * @param {string} appName The name of the application
   *
   * @param {string} ownerName The name of the owner
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {string} [options.orderby] the OData-like $orderby argument. Possible
   * values include: 'last_occurrence asc', 'last_occurrence desc', 'count asc',
   * 'count desc', 'display_id asc', 'display_id desc', 'impacted_users asc',
   * 'impacted_users desc'
   *
   * @param {string} [options.appVersion] version
   *
   * @param {string} [options.continuationToken] Cassandra request continuation
   * token. The token is used for pagination.
   *
   * @param {string} [options.groupStatus] Possible values include: 'open',
   * 'closed', 'ignored'
   *
   * @param {string} [options.groupTextSearch] A freetext search that matches in
   * crash, crash types, crash stack_traces and crash user
   *
   * @param {string} [options.groupType] Possible values include: 'GroupType1',
   * 'GroupType2'
   *
   * @param {boolean} [options.includeUserCounts] if true include impacted user
   * counts in crash group results
   *
   * @param {date} [options.lastOccurrenceFrom] Earliest date when the last time
   * a crash occured in a crash group
   *
   * @param {date} [options.lastOccurrenceTo] Latest date when the last time a
   * crash occured in a crash group
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<CrashGroupsContainer>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  listWithHttpOperationResponse(appName, ownerName, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._list(appName, ownerName, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * @summary Gets a list of crash groups and whether the list contains all
   * available groups.
   *
   * Gets a list of crash groups and whether the list contains all available
   * groups.
   *
   * @param {string} appName The name of the application
   *
   * @param {string} ownerName The name of the owner
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {string} [options.orderby] the OData-like $orderby argument. Possible
   * values include: 'last_occurrence asc', 'last_occurrence desc', 'count asc',
   * 'count desc', 'display_id asc', 'display_id desc', 'impacted_users asc',
   * 'impacted_users desc'
   *
   * @param {string} [options.appVersion] version
   *
   * @param {string} [options.continuationToken] Cassandra request continuation
   * token. The token is used for pagination.
   *
   * @param {string} [options.groupStatus] Possible values include: 'open',
   * 'closed', 'ignored'
   *
   * @param {string} [options.groupTextSearch] A freetext search that matches in
   * crash, crash types, crash stack_traces and crash user
   *
   * @param {string} [options.groupType] Possible values include: 'GroupType1',
   * 'GroupType2'
   *
   * @param {boolean} [options.includeUserCounts] if true include impacted user
   * counts in crash group results
   *
   * @param {date} [options.lastOccurrenceFrom] Earliest date when the last time
   * a crash occured in a crash group
   *
   * @param {date} [options.lastOccurrenceTo] Latest date when the last time a
   * crash occured in a crash group
   *
   * @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 {CrashGroupsContainer} - 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 CrashGroupsContainer} for more information.
   *
   *                      {object} [request]  - The HTTP Request object if an error did not occur.
   *
   *                      {stream} [response] - The HTTP Response stream if an error did not occur.
   */
  list(appName, ownerName, options, optionalCallback) {
    let client = this.client;
    let self = this;
    if (!optionalCallback && typeof options === 'function') {
      optionalCallback = options;
      options = null;
    }
    if (!optionalCallback) {
      return new Promise((resolve, reject) => {
        self._list(appName, ownerName, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._list(appName, ownerName, options, optionalCallback);
    }
  }

  /**
   * Gets a specific group
   *
   * @param {string} appName The name of the application
   *
   * @param {string} crashGroupId id of a specific group
   *
   * @param {string} ownerName The name of the owner
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {boolean} [options.includeUserCounts] if true include impacted user
   * counts in crash group results
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<CrashGroup>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  getWithHttpOperationResponse(appName, crashGroupId, ownerName, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._get(appName, crashGroupId, ownerName, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Gets a specific group
   *
   * @param {string} appName The name of the application
   *
   * @param {string} crashGroupId id of a specific group
   *
   * @param {string} ownerName The name of the owner
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {boolean} [options.includeUserCounts] if true include impacted user
   * counts in crash group results
   *
   * @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 {CrashGroup} - 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 CrashGroup} 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(appName, crashGroupId, ownerName, 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(appName, crashGroupId, ownerName, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._get(appName, crashGroupId, ownerName, options, optionalCallback);
    }
  }

  /**
   * Updates a group
   *
   * @param {string} appName The name of the application
   *
   * @param {string} crashGroupId id of a specific group
   *
   * @param {object} group Group change object. All fields are optional and only
   * provided fields will get updated.
   *
   * @param {object} [group.status]
   *
   * @param {string} [group.annotation]
   *
   * @param {string} ownerName The name of the owner
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {boolean} [options.includeUserCounts] if true include impacted user
   * counts in crash group results
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<CrashGroup>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  updateWithHttpOperationResponse(appName, crashGroupId, group, ownerName, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._update(appName, crashGroupId, group, ownerName, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Updates a group
   *
   * @param {string} appName The name of the application
   *
   * @param {string} crashGroupId id of a specific group
   *
   * @param {object} group Group change object. All fields are optional and only
   * provided fields will get updated.
   *
   * @param {object} [group.status]
   *
   * @param {string} [group.annotation]
   *
   * @param {string} ownerName The name of the owner
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {boolean} [options.includeUserCounts] if true include impacted user
   * counts in crash group results
   *
   * @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 {CrashGroup} - 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 CrashGroup} 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.
   */
  update(appName, crashGroupId, group, ownerName, 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(appName, crashGroupId, group, ownerName, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._update(appName, crashGroupId, group, ownerName, options, optionalCallback);
    }
  }

  /**
   * Gets a stacktrace for a specific crash
   *
   * @param {string} appName The name of the application
   *
   * @param {string} crashGroupId id of a specific group
   *
   * @param {string} ownerName The name of the owner
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {boolean} [options.groupingOnly] true if the stacktrace should be
   * only the relevant thread / exception. Default is false
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<Stacktrace>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  getStacktraceWithHttpOperationResponse(appName, crashGroupId, ownerName, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._getStacktrace(appName, crashGroupId, ownerName, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Gets a stacktrace for a specific crash
   *
   * @param {string} appName The name of the application
   *
   * @param {string} crashGroupId id of a specific group
   *
   * @param {string} ownerName The name of the owner
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {boolean} [options.groupingOnly] true if the stacktrace should be
   * only the relevant thread / exception. Default is false
   *
   * @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 {Stacktrace} - 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 Stacktrace} 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.
   */
  getStacktrace(appName, crashGroupId, ownerName, 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._getStacktrace(appName, crashGroupId, ownerName, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._getStacktrace(appName, crashGroupId, ownerName, options, optionalCallback);
    }
  }

}

module.exports = CrashGroups;
