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

/**
 * Gets a list of Analytics Items defined within an Application Insights
 * component.
 *
 * @param {string} resourceGroupName The name of the resource group.
 *
 * @param {string} resourceName The name of the Application Insights component
 * resource.
 *
 * @param {string} scopePath Enum indicating if this item definition is owned
 * by a specific user or is shared between all users with access to the
 * Application Insights component. Possible values include: 'analyticsItems',
 * 'myanalyticsItems'
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {string} [options.scope] Enum indicating if this item definition is
 * owned by a specific user or is shared between all users with access to the
 * Application Insights component. Possible values include: 'shared', 'user'
 *
 * @param {string} [options.type] Enum indicating the type of the Analytics
 * item. Possible values include: 'none', 'query', 'function', 'folder',
 * 'recent'
 *
 * @param {boolean} [options.includeContent] Flag indicating whether or not to
 * return the content of each applicable item. If false, only return the item
 * information.
 *
 * @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.
 *
 *                      {array} [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 _list(resourceGroupName, resourceName, scopePath, 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 scope = (options && options.scope !== undefined) ? options.scope : 'shared';
  let type = (options && options.type !== undefined) ? options.type : 'none';
  let includeContent = (options && options.includeContent !== undefined) ? options.includeContent : undefined;
  // Validate
  try {
    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 (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 (resourceName === null || resourceName === undefined || typeof resourceName.valueOf() !== 'string') {
      throw new Error('resourceName cannot be null or undefined and it must be of type string.');
    }
    if (scopePath === null || scopePath === undefined || typeof scopePath.valueOf() !== 'string') {
      throw new Error('scopePath 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 (scope !== null && scope !== undefined && typeof scope.valueOf() !== 'string') {
      throw new Error('scope must be of type string.');
    }
    if (type !== null && type !== undefined && typeof type.valueOf() !== 'string') {
      throw new Error('type must be of type string.');
    }
    if (includeContent !== null && includeContent !== undefined && typeof includeContent !== 'boolean') {
      throw new Error('includeContent 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.insights/components/{resourceName}/{scopePath}';
  requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
  requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
  requestUrl = requestUrl.replace('{resourceName}', encodeURIComponent(resourceName));
  requestUrl = requestUrl.replace('{scopePath}', encodeURIComponent(scopePath));
  let queryParameters = [];
  queryParameters.push('api-version=' + encodeURIComponent(this.client.apiVersion));
  if (scope !== null && scope !== undefined) {
    queryParameters.push('scope=' + encodeURIComponent(scope));
  }
  if (type !== null && type !== undefined) {
    queryParameters.push('type=' + encodeURIComponent(type));
  }
  if (includeContent !== null && includeContent !== undefined) {
    queryParameters.push('includeContent=' + encodeURIComponent(includeContent.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) {
          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 = {
            required: false,
            serializedName: 'parsedResponse',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'ApplicationInsightsComponentAnalyticsItemElementType',
                  type: {
                    name: 'Composite',
                    className: 'ApplicationInsightsComponentAnalyticsItem'
                  }
              }
            }
          };
          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 Analytics Items defined within an Application Insights
 * component.
 *
 * @param {string} resourceGroupName The name of the resource group.
 *
 * @param {string} resourceName The name of the Application Insights component
 * resource.
 *
 * @param {string} scopePath Enum indicating if this item definition is owned
 * by a specific user or is shared between all users with access to the
 * Application Insights component. Possible values include: 'analyticsItems',
 * 'myanalyticsItems'
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {string} [options.id] The Id of a specific item defined in the
 * Application Insights component
 *
 * @param {string} [options.name] The name of a specific item defined in the
 * Application Insights component
 *
 * @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 ApplicationInsightsComponentAnalyticsItem}
 *                      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, resourceName, scopePath, 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 id = (options && options.id !== undefined) ? options.id : undefined;
  let name = (options && options.name !== undefined) ? options.name : undefined;
  // Validate
  try {
    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 (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 (resourceName === null || resourceName === undefined || typeof resourceName.valueOf() !== 'string') {
      throw new Error('resourceName cannot be null or undefined and it must be of type string.');
    }
    if (scopePath === null || scopePath === undefined || typeof scopePath.valueOf() !== 'string') {
      throw new Error('scopePath 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 (id !== null && id !== undefined && typeof id.valueOf() !== 'string') {
      throw new Error('id must be of type string.');
    }
    if (name !== null && name !== undefined && typeof name.valueOf() !== 'string') {
      throw new Error('name 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.insights/components/{resourceName}/{scopePath}/item';
  requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
  requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
  requestUrl = requestUrl.replace('{resourceName}', encodeURIComponent(resourceName));
  requestUrl = requestUrl.replace('{scopePath}', encodeURIComponent(scopePath));
  let queryParameters = [];
  queryParameters.push('api-version=' + encodeURIComponent(this.client.apiVersion));
  if (id !== null && id !== undefined) {
    queryParameters.push('id=' + encodeURIComponent(id));
  }
  if (name !== null && name !== undefined) {
    queryParameters.push('name=' + encodeURIComponent(name));
  }
  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['ApplicationInsightsComponentAnalyticsItem']().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);
  });
}

/**
 * Adds or Updates a specific Analytics Item within an Application Insights
 * component.
 *
 * @param {string} resourceGroupName The name of the resource group.
 *
 * @param {string} resourceName The name of the Application Insights component
 * resource.
 *
 * @param {string} scopePath Enum indicating if this item definition is owned
 * by a specific user or is shared between all users with access to the
 * Application Insights component. Possible values include: 'analyticsItems',
 * 'myanalyticsItems'
 *
 * @param {object} itemProperties Properties that need to be specified to
 * create a new item and add it to an Application Insights component.
 *
 * @param {string} [itemProperties.id] Internally assigned unique id of the
 * item definition.
 *
 * @param {string} [itemProperties.name] The user-defined name of the item.
 *
 * @param {string} [itemProperties.content] The content of this item
 *
 * @param {string} [itemProperties.scope] Enum indicating if this item
 * definition is owned by a specific user or is shared between all users with
 * access to the Application Insights component. Possible values include:
 * 'shared', 'user'
 *
 * @param {string} [itemProperties.type] Enum indicating the type of the
 * Analytics item. Possible values include: 'query', 'function', 'folder',
 * 'recent'
 *
 * @param {object} [itemProperties.properties]
 *
 * @param {string} [itemProperties.properties.functionAlias] A function alias,
 * used when the type of the item is Function
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {boolean} [options.overrideItem] Flag indicating whether or not to
 * force save an item. This allows overriding an item if it already exists.
 *
 * @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 ApplicationInsightsComponentAnalyticsItem}
 *                      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 _put(resourceGroupName, resourceName, scopePath, itemProperties, 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 overrideItem = (options && options.overrideItem !== undefined) ? options.overrideItem : undefined;
  // Validate
  try {
    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 (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 (resourceName === null || resourceName === undefined || typeof resourceName.valueOf() !== 'string') {
      throw new Error('resourceName cannot be null or undefined and it must be of type string.');
    }
    if (scopePath === null || scopePath === undefined || typeof scopePath.valueOf() !== 'string') {
      throw new Error('scopePath 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 (overrideItem !== null && overrideItem !== undefined && typeof overrideItem !== 'boolean') {
      throw new Error('overrideItem must be of type boolean.');
    }
    if (itemProperties === null || itemProperties === undefined) {
      throw new Error('itemProperties cannot be null or undefined.');
    }
    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.insights/components/{resourceName}/{scopePath}/item';
  requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
  requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
  requestUrl = requestUrl.replace('{resourceName}', encodeURIComponent(resourceName));
  requestUrl = requestUrl.replace('{scopePath}', encodeURIComponent(scopePath));
  let queryParameters = [];
  queryParameters.push('api-version=' + encodeURIComponent(this.client.apiVersion));
  if (overrideItem !== null && overrideItem !== undefined) {
    queryParameters.push('overrideItem=' + encodeURIComponent(overrideItem.toString()));
  }
  if (queryParameters.length > 0) {
    requestUrl += '?' + queryParameters.join('&');
  }

  // Create HTTP transport objects
  let httpRequest = new WebResource();
  httpRequest.method = 'PUT';
  httpRequest.url = requestUrl;
  httpRequest.headers = {};
  // Set Headers
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  if (this.client.generateClientRequestId) {
      httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if(options) {
    for(let headerName in options['customHeaders']) {
      if (options['customHeaders'].hasOwnProperty(headerName)) {
        httpRequest.headers[headerName] = options['customHeaders'][headerName];
      }
    }
  }
  // Serialize Request
  let requestContent = null;
  let requestModel = null;
  try {
    if (itemProperties !== null && itemProperties !== undefined) {
      let requestModelMapper = new client.models['ApplicationInsightsComponentAnalyticsItem']().mapper();
      requestModel = client.serialize(requestModelMapper, itemProperties, 'itemProperties');
      requestContent = JSON.stringify(requestModel);
    }
  } catch (error) {
    let serializationError = new Error(`Error "${error.message}" occurred in serializing the ` +
        `payload - ${JSON.stringify(itemProperties, 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) {
          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['ApplicationInsightsComponentAnalyticsItem']().mapper();
          result = client.deserialize(resultMapper, parsedResponse, 'result');
        }
      } catch (error) {
        let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`);
        deserializationError.request = msRest.stripRequest(httpRequest);
        deserializationError.response = msRest.stripResponse(response);
        return callback(deserializationError);
      }
    }

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

/**
 * Deletes a specific Analytics Items defined within an Application Insights
 * component.
 *
 * @param {string} resourceGroupName The name of the resource group.
 *
 * @param {string} resourceName The name of the Application Insights component
 * resource.
 *
 * @param {string} scopePath Enum indicating if this item definition is owned
 * by a specific user or is shared between all users with access to the
 * Application Insights component. Possible values include: 'analyticsItems',
 * 'myanalyticsItems'
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {string} [options.id] The Id of a specific item defined in the
 * Application Insights component
 *
 * @param {string} [options.name] The name of a specific item defined in the
 * Application Insights component
 *
 * @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, resourceName, scopePath, 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 id = (options && options.id !== undefined) ? options.id : undefined;
  let name = (options && options.name !== undefined) ? options.name : undefined;
  // Validate
  try {
    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 (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 (resourceName === null || resourceName === undefined || typeof resourceName.valueOf() !== 'string') {
      throw new Error('resourceName cannot be null or undefined and it must be of type string.');
    }
    if (scopePath === null || scopePath === undefined || typeof scopePath.valueOf() !== 'string') {
      throw new Error('scopePath 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 (id !== null && id !== undefined && typeof id.valueOf() !== 'string') {
      throw new Error('id must be of type string.');
    }
    if (name !== null && name !== undefined && typeof name.valueOf() !== 'string') {
      throw new Error('name 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.insights/components/{resourceName}/{scopePath}/item';
  requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
  requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
  requestUrl = requestUrl.replace('{resourceName}', encodeURIComponent(resourceName));
  requestUrl = requestUrl.replace('{scopePath}', encodeURIComponent(scopePath));
  let queryParameters = [];
  queryParameters.push('api-version=' + encodeURIComponent(this.client.apiVersion));
  if (id !== null && id !== undefined) {
    queryParameters.push('id=' + encodeURIComponent(id));
  }
  if (name !== null && name !== undefined) {
    queryParameters.push('name=' + encodeURIComponent(name));
  }
  if (queryParameters.length > 0) {
    requestUrl += '?' + queryParameters.join('&');
  }

  // Create HTTP transport objects
  let httpRequest = new WebResource();
  httpRequest.method = 'DELETE';
  httpRequest.url = requestUrl;
  httpRequest.headers = {};
  // Set Headers
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  if (this.client.generateClientRequestId) {
      httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if(options) {
    for(let headerName in options['customHeaders']) {
      if (options['customHeaders'].hasOwnProperty(headerName)) {
        httpRequest.headers[headerName] = options['customHeaders'][headerName];
      }
    }
  }
  httpRequest.body = null;
  // Send Request
  return client.pipeline(httpRequest, (err, response, responseBody) => {
    if (err) {
      return callback(err);
    }
    let statusCode = response.statusCode;
    if (statusCode !== 200) {
      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;

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

/** Class representing a AnalyticsItem. */
class AnalyticsItem {
  /**
   * Create a AnalyticsItem.
   * @param {ApplicationInsightsManagementClient} client Reference to the service client.
   */
  constructor(client) {
    this.client = client;
    this._list = _list;
    this._get = _get;
    this._put = _put;
    this._deleteMethod = _deleteMethod;
  }

  /**
   * Gets a list of Analytics Items defined within an Application Insights
   * component.
   *
   * @param {string} resourceGroupName The name of the resource group.
   *
   * @param {string} resourceName The name of the Application Insights component
   * resource.
   *
   * @param {string} scopePath Enum indicating if this item definition is owned
   * by a specific user or is shared between all users with access to the
   * Application Insights component. Possible values include: 'analyticsItems',
   * 'myanalyticsItems'
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {string} [options.scope] Enum indicating if this item definition is
   * owned by a specific user or is shared between all users with access to the
   * Application Insights component. Possible values include: 'shared', 'user'
   *
   * @param {string} [options.type] Enum indicating the type of the Analytics
   * item. Possible values include: 'none', 'query', 'function', 'folder',
   * 'recent'
   *
   * @param {boolean} [options.includeContent] Flag indicating whether or not to
   * return the content of each applicable item. If false, only return the item
   * information.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<Array>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  listWithHttpOperationResponse(resourceGroupName, resourceName, scopePath, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._list(resourceGroupName, resourceName, scopePath, 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 list of Analytics Items defined within an Application Insights
   * component.
   *
   * @param {string} resourceGroupName The name of the resource group.
   *
   * @param {string} resourceName The name of the Application Insights component
   * resource.
   *
   * @param {string} scopePath Enum indicating if this item definition is owned
   * by a specific user or is shared between all users with access to the
   * Application Insights component. Possible values include: 'analyticsItems',
   * 'myanalyticsItems'
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {string} [options.scope] Enum indicating if this item definition is
   * owned by a specific user or is shared between all users with access to the
   * Application Insights component. Possible values include: 'shared', 'user'
   *
   * @param {string} [options.type] Enum indicating the type of the Analytics
   * item. Possible values include: 'none', 'query', 'function', 'folder',
   * 'recent'
   *
   * @param {boolean} [options.includeContent] Flag indicating whether or not to
   * return the content of each applicable item. If false, only return the item
   * information.
   *
   * @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 {Array} - 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.
   *
   *                      {array} [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.
   */
  list(resourceGroupName, resourceName, scopePath, options, optionalCallback) {
    let client = this.client;
    let self = this;
    if (!optionalCallback && typeof options === 'function') {
      optionalCallback = options;
      options = null;
    }
    if (!optionalCallback) {
      return new Promise((resolve, reject) => {
        self._list(resourceGroupName, resourceName, scopePath, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._list(resourceGroupName, resourceName, scopePath, options, optionalCallback);
    }
  }

  /**
   * Gets a specific Analytics Items defined within an Application Insights
   * component.
   *
   * @param {string} resourceGroupName The name of the resource group.
   *
   * @param {string} resourceName The name of the Application Insights component
   * resource.
   *
   * @param {string} scopePath Enum indicating if this item definition is owned
   * by a specific user or is shared between all users with access to the
   * Application Insights component. Possible values include: 'analyticsItems',
   * 'myanalyticsItems'
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {string} [options.id] The Id of a specific item defined in the
   * Application Insights component
   *
   * @param {string} [options.name] The name of a specific item defined in the
   * Application Insights component
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<ApplicationInsightsComponentAnalyticsItem>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  getWithHttpOperationResponse(resourceGroupName, resourceName, scopePath, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._get(resourceGroupName, resourceName, scopePath, 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 Analytics Items defined within an Application Insights
   * component.
   *
   * @param {string} resourceGroupName The name of the resource group.
   *
   * @param {string} resourceName The name of the Application Insights component
   * resource.
   *
   * @param {string} scopePath Enum indicating if this item definition is owned
   * by a specific user or is shared between all users with access to the
   * Application Insights component. Possible values include: 'analyticsItems',
   * 'myanalyticsItems'
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {string} [options.id] The Id of a specific item defined in the
   * Application Insights component
   *
   * @param {string} [options.name] The name of a specific item defined in the
   * Application Insights component
   *
   * @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 {ApplicationInsightsComponentAnalyticsItem} - 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 ApplicationInsightsComponentAnalyticsItem}
   *                      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, resourceName, scopePath, 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, resourceName, scopePath, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._get(resourceGroupName, resourceName, scopePath, options, optionalCallback);
    }
  }

  /**
   * Adds or Updates a specific Analytics Item within an Application Insights
   * component.
   *
   * @param {string} resourceGroupName The name of the resource group.
   *
   * @param {string} resourceName The name of the Application Insights component
   * resource.
   *
   * @param {string} scopePath Enum indicating if this item definition is owned
   * by a specific user or is shared between all users with access to the
   * Application Insights component. Possible values include: 'analyticsItems',
   * 'myanalyticsItems'
   *
   * @param {object} itemProperties Properties that need to be specified to
   * create a new item and add it to an Application Insights component.
   *
   * @param {string} [itemProperties.id] Internally assigned unique id of the
   * item definition.
   *
   * @param {string} [itemProperties.name] The user-defined name of the item.
   *
   * @param {string} [itemProperties.content] The content of this item
   *
   * @param {string} [itemProperties.scope] Enum indicating if this item
   * definition is owned by a specific user or is shared between all users with
   * access to the Application Insights component. Possible values include:
   * 'shared', 'user'
   *
   * @param {string} [itemProperties.type] Enum indicating the type of the
   * Analytics item. Possible values include: 'query', 'function', 'folder',
   * 'recent'
   *
   * @param {object} [itemProperties.properties]
   *
   * @param {string} [itemProperties.properties.functionAlias] A function alias,
   * used when the type of the item is Function
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {boolean} [options.overrideItem] Flag indicating whether or not to
   * force save an item. This allows overriding an item if it already exists.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<ApplicationInsightsComponentAnalyticsItem>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  putWithHttpOperationResponse(resourceGroupName, resourceName, scopePath, itemProperties, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._put(resourceGroupName, resourceName, scopePath, itemProperties, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Adds or Updates a specific Analytics Item within an Application Insights
   * component.
   *
   * @param {string} resourceGroupName The name of the resource group.
   *
   * @param {string} resourceName The name of the Application Insights component
   * resource.
   *
   * @param {string} scopePath Enum indicating if this item definition is owned
   * by a specific user or is shared between all users with access to the
   * Application Insights component. Possible values include: 'analyticsItems',
   * 'myanalyticsItems'
   *
   * @param {object} itemProperties Properties that need to be specified to
   * create a new item and add it to an Application Insights component.
   *
   * @param {string} [itemProperties.id] Internally assigned unique id of the
   * item definition.
   *
   * @param {string} [itemProperties.name] The user-defined name of the item.
   *
   * @param {string} [itemProperties.content] The content of this item
   *
   * @param {string} [itemProperties.scope] Enum indicating if this item
   * definition is owned by a specific user or is shared between all users with
   * access to the Application Insights component. Possible values include:
   * 'shared', 'user'
   *
   * @param {string} [itemProperties.type] Enum indicating the type of the
   * Analytics item. Possible values include: 'query', 'function', 'folder',
   * 'recent'
   *
   * @param {object} [itemProperties.properties]
   *
   * @param {string} [itemProperties.properties.functionAlias] A function alias,
   * used when the type of the item is Function
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {boolean} [options.overrideItem] Flag indicating whether or not to
   * force save an item. This allows overriding an item if it already exists.
   *
   * @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 {ApplicationInsightsComponentAnalyticsItem} - 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 ApplicationInsightsComponentAnalyticsItem}
   *                      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.
   */
  put(resourceGroupName, resourceName, scopePath, itemProperties, 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._put(resourceGroupName, resourceName, scopePath, itemProperties, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._put(resourceGroupName, resourceName, scopePath, itemProperties, options, optionalCallback);
    }
  }

  /**
   * Deletes a specific Analytics Items defined within an Application Insights
   * component.
   *
   * @param {string} resourceGroupName The name of the resource group.
   *
   * @param {string} resourceName The name of the Application Insights component
   * resource.
   *
   * @param {string} scopePath Enum indicating if this item definition is owned
   * by a specific user or is shared between all users with access to the
   * Application Insights component. Possible values include: 'analyticsItems',
   * 'myanalyticsItems'
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {string} [options.id] The Id of a specific item defined in the
   * Application Insights component
   *
   * @param {string} [options.name] The name of a specific item defined in the
   * Application Insights component
   *
   * @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, resourceName, scopePath, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._deleteMethod(resourceGroupName, resourceName, scopePath, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Deletes a specific Analytics Items defined within an Application Insights
   * component.
   *
   * @param {string} resourceGroupName The name of the resource group.
   *
   * @param {string} resourceName The name of the Application Insights component
   * resource.
   *
   * @param {string} scopePath Enum indicating if this item definition is owned
   * by a specific user or is shared between all users with access to the
   * Application Insights component. Possible values include: 'analyticsItems',
   * 'myanalyticsItems'
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {string} [options.id] The Id of a specific item defined in the
   * Application Insights component
   *
   * @param {string} [options.name] The name of a specific item defined in the
   * Application Insights component
   *
   * @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, resourceName, scopePath, 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, resourceName, scopePath, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._deleteMethod(resourceGroupName, resourceName, scopePath, options, optionalCallback);
    }
  }

}

module.exports = AnalyticsItem;
