/*
 * 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 WebResource = msRest.WebResource;
const moment = require('moment');

/**
 * @summary Retrieve metric data
 *
 * Gets metric values for a single metric
 *
 * @param {string} appId ID of the application. This is Application ID from the
 * API Access settings blade in the Azure portal.
 *
 * @param {string} metricId ID of the metric. This is either a standard AI
 * metric, or an application-specific custom metric. Possible values include:
 * 'requests/count', 'requests/duration', 'requests/failed', 'users/count',
 * 'users/authenticated', 'pageViews/count', 'pageViews/duration',
 * 'client/processingDuration', 'client/receiveDuration',
 * 'client/networkDuration', 'client/sendDuration', 'client/totalDuration',
 * 'dependencies/count', 'dependencies/failed', 'dependencies/duration',
 * 'exceptions/count', 'exceptions/browser', 'exceptions/server',
 * 'sessions/count', 'performanceCounters/requestExecutionTime',
 * 'performanceCounters/requestsPerSecond',
 * 'performanceCounters/requestsInQueue',
 * 'performanceCounters/memoryAvailableBytes',
 * 'performanceCounters/exceptionsPerSecond',
 * 'performanceCounters/processCpuPercentage',
 * 'performanceCounters/processIOBytesPerSecond',
 * 'performanceCounters/processPrivateBytes',
 * 'performanceCounters/processorCpuPercentage',
 * 'availabilityResults/availabilityPercentage',
 * 'availabilityResults/duration', 'billing/telemetryCount',
 * 'customEvents/count'
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {string} [options.timespan] The timespan over which to retrieve
 * metric values. This is an ISO8601 time period value. If timespan is omitted,
 * a default time range of `PT12H` ("last 12 hours") is used. The actual
 * timespan that is queried may be adjusted by the server based. In all cases,
 * the actual time span used for the query is included in the response.
 *
 * @param {moment.duration} [options.interval] The time interval to use when
 * retrieving metric values. This is an ISO8601 duration. If interval is
 * omitted, the metric value is aggregated across the entire timespan. If
 * interval is supplied, the server may adjust the interval to a more
 * appropriate size based on the timespan used for the query. In all cases, the
 * actual interval used for the query is included in the response.
 *
 * @param {array} [options.aggregation] The aggregation to use when computing
 * the metric values. To retrieve more than one aggregation at a time, separate
 * them with a comma. If no aggregation is specified, then the default
 * aggregation for the metric is used.
 *
 * @param {array} [options.segment] The name of the dimension to segment the
 * metric values by. This dimension must be applicable to the metric you are
 * retrieving. To segment by more than one dimension at a time, separate them
 * with a comma (,). In this case, the metric data will be segmented in the
 * order the dimensions are listed in the parameter.
 *
 * @param {number} [options.top] The number of segments to return.  This value
 * is only valid when segment is specified.
 *
 * @param {string} [options.orderby] The aggregation function and direction to
 * sort the segments by.  This value is only valid when segment is specified.
 *
 * @param {string} [options.filter] An expression used to filter the results.
 * This value should be a valid OData filter expression where the keys of each
 * clause should be applicable dimensions for the metric you are retrieving.
 *
 * @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 MetricsResult} 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(appId, metricId, 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 timespan = (options && options.timespan !== undefined) ? options.timespan : undefined;
  let interval = (options && options.interval !== undefined) ? options.interval : undefined;
  let aggregation = (options && options.aggregation !== undefined) ? options.aggregation : undefined;
  let segment = (options && options.segment !== undefined) ? options.segment : undefined;
  let top = (options && options.top !== undefined) ? options.top : undefined;
  let orderby = (options && options.orderby !== undefined) ? options.orderby : undefined;
  let filter = (options && options.filter !== undefined) ? options.filter : undefined;
  // Validate
  try {
    if (appId === null || appId === undefined || typeof appId.valueOf() !== 'string') {
      throw new Error('appId cannot be null or undefined and it must be of type string.');
    }
    if (metricId === null || metricId === undefined || typeof metricId.valueOf() !== 'string') {
      throw new Error('metricId cannot be null or undefined and it must be of type string.');
    }
    if (timespan !== null && timespan !== undefined && typeof timespan.valueOf() !== 'string') {
      throw new Error('timespan must be of type string.');
    }
    if(interval && !moment.isDuration(interval)) {
      throw new Error('interval must be of type moment.duration.');
    }
    if (Array.isArray(aggregation)) {
      for (let i = 0; i < aggregation.length; i++) {
        if (aggregation[i] !== null && aggregation[i] !== undefined && typeof aggregation[i].valueOf() !== 'string') {
          throw new Error('aggregation[i] must be of type string.');
        }
      }
    }
    if (aggregation !== null && aggregation !== undefined) {
      if (aggregation.length < 1)
      {
        throw new Error('"aggregation" should satisfy the constraint - "MinItems": 1');
      }
    }
    if (Array.isArray(segment)) {
      for (let i1 = 0; i1 < segment.length; i1++) {
        if (segment[i1] !== null && segment[i1] !== undefined && typeof segment[i1].valueOf() !== 'string') {
          throw new Error('segment[i1] must be of type string.');
        }
      }
    }
    if (segment !== null && segment !== undefined) {
      if (segment.length < 1)
      {
        throw new Error('"segment" should satisfy the constraint - "MinItems": 1');
      }
    }
    if (top !== null && top !== undefined && typeof top !== 'number') {
      throw new Error('top must be of type number.');
    }
    if (orderby !== null && orderby !== undefined && typeof orderby.valueOf() !== 'string') {
      throw new Error('orderby must be of type string.');
    }
    if (filter !== null && filter !== undefined && typeof filter.valueOf() !== 'string') {
      throw new Error('filter must be of type string.');
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  let baseUrl = this.client.baseUri;
  let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'apps/{appId}/metrics/{metricId}';
  requestUrl = requestUrl.replace('{appId}', encodeURIComponent(appId));
  requestUrl = requestUrl.replace('{metricId}', encodeURIComponent(metricId));
  let queryParameters = [];
  if (timespan !== null && timespan !== undefined) {
    queryParameters.push('timespan=' + encodeURIComponent(timespan));
  }
  if (interval !== null && interval !== undefined) {
    queryParameters.push('interval=' + encodeURIComponent(interval.toISOString()));
  }
  if (aggregation !== null && aggregation !== undefined) {
    queryParameters.push('aggregation=' + encodeURIComponent(aggregation.join(',')));
  }
  if (segment !== null && segment !== undefined) {
    queryParameters.push('segment=' + encodeURIComponent(segment.join(',')));
  }
  if (top !== null && top !== undefined) {
    queryParameters.push('top=' + encodeURIComponent(top.toString()));
  }
  if (orderby !== null && orderby !== undefined) {
    queryParameters.push('orderby=' + encodeURIComponent(orderby));
  }
  if (filter !== null && filter !== undefined) {
    queryParameters.push('filter=' + encodeURIComponent(filter));
  }
  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;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          let resultMapper = new client.models['ErrorResponse']().mapper();
          error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
        }
      } catch (defaultError) {
        error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
                         `- "${responseBody}" for the default response.`;
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    let result = null;
    if (responseBody === '') responseBody = null;
    // Deserialize Response
    if (statusCode === 200) {
      let parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          let resultMapper = new client.models['MetricsResult']().mapper();
          result = client.deserialize(resultMapper, parsedResponse, 'result');
        }
      } catch (error) {
        let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`);
        deserializationError.request = msRest.stripRequest(httpRequest);
        deserializationError.response = msRest.stripResponse(response);
        return callback(deserializationError);
      }
    }

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

/**
 * @summary Retrieve metric data
 *
 * Gets metric values for multiple metrics
 *
 * @param {string} appId ID of the application. This is Application ID from the
 * API Access settings blade in the Azure portal.
 *
 * @param {array} body The batched metrics query.
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {object} [options.customHeaders] Headers that will be added to the
 * request
 *
 * @param {function} callback - The callback.
 *
 * @returns {function} callback(err, result, request, response)
 *
 *                      {Error}  err        - The Error object if an error occurred, null otherwise.
 *
 *                      {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 _getMultiple(appId, body, options, callback) {
   /* jshint validthis: true */
  let client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }
  // Validate
  try {
    if (appId === null || appId === undefined || typeof appId.valueOf() !== 'string') {
      throw new Error('appId 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('/') ? '' : '/') + 'apps/{appId}/metrics';
  requestUrl = requestUrl.replace('{appId}', encodeURIComponent(appId));

  // Create HTTP transport objects
  let httpRequest = new WebResource();
  httpRequest.method = 'POST';
  httpRequest.url = requestUrl;
  httpRequest.headers = {};
  // Set Headers
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  if(options) {
    for(let headerName in options['customHeaders']) {
      if (options['customHeaders'].hasOwnProperty(headerName)) {
        httpRequest.headers[headerName] = options['customHeaders'][headerName];
      }
    }
  }
  // Serialize Request
  let requestContent = null;
  let requestModel = null;
  try {
    if (body !== null && body !== undefined) {
      let requestModelMapper = {
        required: true,
        serializedName: 'body',
        type: {
          name: 'Sequence',
          element: {
              required: false,
              serializedName: 'MetricsPostBodySchemaElementType',
              type: {
                name: 'Composite',
                className: 'MetricsPostBodySchema'
              }
          }
        }
      };
      requestModel = client.serialize(requestModelMapper, body, 'body');
      requestContent = JSON.stringify(requestModel);
    }
  } catch (error) {
    let serializationError = new Error(`Error "${error.message}" occurred in serializing the ` +
        `payload - ${JSON.stringify(body, null, 2)}.`);
    return callback(serializationError);
  }
  httpRequest.body = requestContent;
  // Send Request
  return client.pipeline(httpRequest, (err, response, responseBody) => {
    if (err) {
      return callback(err);
    }
    let statusCode = response.statusCode;
    if (statusCode !== 200) {
      let error = new Error(responseBody);
      error.statusCode = response.statusCode;
      error.request = msRest.stripRequest(httpRequest);
      error.response = msRest.stripResponse(response);
      if (responseBody === '') responseBody = null;
      let parsedErrorResponse;
      try {
        parsedErrorResponse = JSON.parse(responseBody);
        if (parsedErrorResponse) {
          let internalError = null;
          if (parsedErrorResponse.error) internalError = parsedErrorResponse.error;
          error.code = internalError ? internalError.code : parsedErrorResponse.code;
          error.message = internalError ? internalError.message : parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          let resultMapper = new client.models['ErrorResponse']().mapper();
          error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
        }
      } catch (defaultError) {
        error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
                         `- "${responseBody}" for the default response.`;
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    let result = null;
    if (responseBody === '') responseBody = null;
    // Deserialize Response
    if (statusCode === 200) {
      let parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          let resultMapper = {
            required: false,
            serializedName: 'parsedResponse',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'MetricsResultsItemElementType',
                  type: {
                    name: 'Composite',
                    className: 'MetricsResultsItem'
                  }
              }
            }
          };
          result = client.deserialize(resultMapper, parsedResponse, 'result');
        }
      } catch (error) {
        let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`);
        deserializationError.request = msRest.stripRequest(httpRequest);
        deserializationError.response = msRest.stripResponse(response);
        return callback(deserializationError);
      }
    }

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

/**
 * @summary Retrieve metric metatadata
 *
 * Gets metadata describing the available metrics
 *
 * @param {string} appId ID of the application. This is Application ID from the
 * API Access settings blade in the Azure portal.
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {object} [options.customHeaders] Headers that will be added to the
 * request
 *
 * @param {function} callback - The callback.
 *
 * @returns {function} callback(err, result, request, response)
 *
 *                      {Error}  err        - The Error object if an error occurred, null otherwise.
 *
 *                      {object} [result]   - The deserialized result object if an error did not occur.
 *
 *                      {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 _getMetadata(appId, options, callback) {
   /* jshint validthis: true */
  let client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }
  // Validate
  try {
    if (appId === null || appId === undefined || typeof appId.valueOf() !== 'string') {
      throw new Error('appId 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('/') ? '' : '/') + 'apps/{appId}/metrics/metadata';
  requestUrl = requestUrl.replace('{appId}', encodeURIComponent(appId));

  // 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;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          let resultMapper = new client.models['ErrorResponse']().mapper();
          error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
        }
      } catch (defaultError) {
        error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
                         `- "${responseBody}" for the default response.`;
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    let result = null;
    if (responseBody === '') responseBody = null;
    // Deserialize Response
    if (statusCode === 200) {
      let parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          let resultMapper = {
            required: false,
            serializedName: 'parsedResponse',
            type: {
              name: 'Object'
            }
          };
          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 Metrics. */
class Metrics {
  /**
   * Create a Metrics.
   * @param {ApplicationInsightsDataClient} client Reference to the service client.
   */
  constructor(client) {
    this.client = client;
    this._get = _get;
    this._getMultiple = _getMultiple;
    this._getMetadata = _getMetadata;
  }

  /**
   * @summary Retrieve metric data
   *
   * Gets metric values for a single metric
   *
   * @param {string} appId ID of the application. This is Application ID from the
   * API Access settings blade in the Azure portal.
   *
   * @param {string} metricId ID of the metric. This is either a standard AI
   * metric, or an application-specific custom metric. Possible values include:
   * 'requests/count', 'requests/duration', 'requests/failed', 'users/count',
   * 'users/authenticated', 'pageViews/count', 'pageViews/duration',
   * 'client/processingDuration', 'client/receiveDuration',
   * 'client/networkDuration', 'client/sendDuration', 'client/totalDuration',
   * 'dependencies/count', 'dependencies/failed', 'dependencies/duration',
   * 'exceptions/count', 'exceptions/browser', 'exceptions/server',
   * 'sessions/count', 'performanceCounters/requestExecutionTime',
   * 'performanceCounters/requestsPerSecond',
   * 'performanceCounters/requestsInQueue',
   * 'performanceCounters/memoryAvailableBytes',
   * 'performanceCounters/exceptionsPerSecond',
   * 'performanceCounters/processCpuPercentage',
   * 'performanceCounters/processIOBytesPerSecond',
   * 'performanceCounters/processPrivateBytes',
   * 'performanceCounters/processorCpuPercentage',
   * 'availabilityResults/availabilityPercentage',
   * 'availabilityResults/duration', 'billing/telemetryCount',
   * 'customEvents/count'
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {string} [options.timespan] The timespan over which to retrieve
   * metric values. This is an ISO8601 time period value. If timespan is omitted,
   * a default time range of `PT12H` ("last 12 hours") is used. The actual
   * timespan that is queried may be adjusted by the server based. In all cases,
   * the actual time span used for the query is included in the response.
   *
   * @param {moment.duration} [options.interval] The time interval to use when
   * retrieving metric values. This is an ISO8601 duration. If interval is
   * omitted, the metric value is aggregated across the entire timespan. If
   * interval is supplied, the server may adjust the interval to a more
   * appropriate size based on the timespan used for the query. In all cases, the
   * actual interval used for the query is included in the response.
   *
   * @param {array} [options.aggregation] The aggregation to use when computing
   * the metric values. To retrieve more than one aggregation at a time, separate
   * them with a comma. If no aggregation is specified, then the default
   * aggregation for the metric is used.
   *
   * @param {array} [options.segment] The name of the dimension to segment the
   * metric values by. This dimension must be applicable to the metric you are
   * retrieving. To segment by more than one dimension at a time, separate them
   * with a comma (,). In this case, the metric data will be segmented in the
   * order the dimensions are listed in the parameter.
   *
   * @param {number} [options.top] The number of segments to return.  This value
   * is only valid when segment is specified.
   *
   * @param {string} [options.orderby] The aggregation function and direction to
   * sort the segments by.  This value is only valid when segment is specified.
   *
   * @param {string} [options.filter] An expression used to filter the results.
   * This value should be a valid OData filter expression where the keys of each
   * clause should be applicable dimensions for the metric you are retrieving.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<MetricsResult>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  getWithHttpOperationResponse(appId, metricId, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._get(appId, metricId, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * @summary Retrieve metric data
   *
   * Gets metric values for a single metric
   *
   * @param {string} appId ID of the application. This is Application ID from the
   * API Access settings blade in the Azure portal.
   *
   * @param {string} metricId ID of the metric. This is either a standard AI
   * metric, or an application-specific custom metric. Possible values include:
   * 'requests/count', 'requests/duration', 'requests/failed', 'users/count',
   * 'users/authenticated', 'pageViews/count', 'pageViews/duration',
   * 'client/processingDuration', 'client/receiveDuration',
   * 'client/networkDuration', 'client/sendDuration', 'client/totalDuration',
   * 'dependencies/count', 'dependencies/failed', 'dependencies/duration',
   * 'exceptions/count', 'exceptions/browser', 'exceptions/server',
   * 'sessions/count', 'performanceCounters/requestExecutionTime',
   * 'performanceCounters/requestsPerSecond',
   * 'performanceCounters/requestsInQueue',
   * 'performanceCounters/memoryAvailableBytes',
   * 'performanceCounters/exceptionsPerSecond',
   * 'performanceCounters/processCpuPercentage',
   * 'performanceCounters/processIOBytesPerSecond',
   * 'performanceCounters/processPrivateBytes',
   * 'performanceCounters/processorCpuPercentage',
   * 'availabilityResults/availabilityPercentage',
   * 'availabilityResults/duration', 'billing/telemetryCount',
   * 'customEvents/count'
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {string} [options.timespan] The timespan over which to retrieve
   * metric values. This is an ISO8601 time period value. If timespan is omitted,
   * a default time range of `PT12H` ("last 12 hours") is used. The actual
   * timespan that is queried may be adjusted by the server based. In all cases,
   * the actual time span used for the query is included in the response.
   *
   * @param {moment.duration} [options.interval] The time interval to use when
   * retrieving metric values. This is an ISO8601 duration. If interval is
   * omitted, the metric value is aggregated across the entire timespan. If
   * interval is supplied, the server may adjust the interval to a more
   * appropriate size based on the timespan used for the query. In all cases, the
   * actual interval used for the query is included in the response.
   *
   * @param {array} [options.aggregation] The aggregation to use when computing
   * the metric values. To retrieve more than one aggregation at a time, separate
   * them with a comma. If no aggregation is specified, then the default
   * aggregation for the metric is used.
   *
   * @param {array} [options.segment] The name of the dimension to segment the
   * metric values by. This dimension must be applicable to the metric you are
   * retrieving. To segment by more than one dimension at a time, separate them
   * with a comma (,). In this case, the metric data will be segmented in the
   * order the dimensions are listed in the parameter.
   *
   * @param {number} [options.top] The number of segments to return.  This value
   * is only valid when segment is specified.
   *
   * @param {string} [options.orderby] The aggregation function and direction to
   * sort the segments by.  This value is only valid when segment is specified.
   *
   * @param {string} [options.filter] An expression used to filter the results.
   * This value should be a valid OData filter expression where the keys of each
   * clause should be applicable dimensions for the metric you are retrieving.
   *
   * @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 {MetricsResult} - 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 MetricsResult} 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(appId, metricId, 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(appId, metricId, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._get(appId, metricId, options, optionalCallback);
    }
  }

  /**
   * @summary Retrieve metric data
   *
   * Gets metric values for multiple metrics
   *
   * @param {string} appId ID of the application. This is Application ID from the
   * API Access settings blade in the Azure portal.
   *
   * @param {array} body The batched metrics query.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<Array>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  getMultipleWithHttpOperationResponse(appId, body, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._getMultiple(appId, body, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * @summary Retrieve metric data
   *
   * Gets metric values for multiple metrics
   *
   * @param {string} appId ID of the application. This is Application ID from the
   * API Access settings blade in the Azure portal.
   *
   * @param {array} body The batched metrics query.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @param {function} [optionalCallback] - The optional callback.
   *
   * @returns {function|Promise} If a callback was passed as the last parameter
   * then it returns the callback else returns a Promise.
   *
   * {Promise} A promise is returned
   *
   *                      @resolve {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.
   */
  getMultiple(appId, body, 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._getMultiple(appId, body, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._getMultiple(appId, body, options, optionalCallback);
    }
  }

  /**
   * @summary Retrieve metric metatadata
   *
   * Gets metadata describing the available metrics
   *
   * @param {string} appId ID of the application. This is Application ID from the
   * API Access settings blade in the Azure portal.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<Object>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  getMetadataWithHttpOperationResponse(appId, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._getMetadata(appId, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * @summary Retrieve metric metatadata
   *
   * Gets metadata describing the available metrics
   *
   * @param {string} appId ID of the application. This is Application ID from the
   * API Access settings blade in the Azure portal.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @param {function} [optionalCallback] - The optional callback.
   *
   * @returns {function|Promise} If a callback was passed as the last parameter
   * then it returns the callback else returns a Promise.
   *
   * {Promise} A promise is returned
   *
   *                      @resolve {Object} - The deserialized result object.
   *
   *                      @reject {Error} - The error object.
   *
   * {function} optionalCallback(err, result, request, response)
   *
   *                      {Error}  err        - The Error object if an error occurred, null otherwise.
   *
   *                      {object} [result]   - The deserialized result object if an error did not occur.
   *
   *                      {object} [request]  - The HTTP Request object if an error did not occur.
   *
   *                      {stream} [response] - The HTTP Response stream if an error did not occur.
   */
  getMetadata(appId, 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._getMetadata(appId, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._getMetadata(appId, options, optionalCallback);
    }
  }

}

module.exports = Metrics;
