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

/**
 * @summary Execute OData query
 *
 * Executes an OData query for events
 *
 * @param {string} appId ID of the application. This is Application ID from the
 * API Access settings blade in the Azure portal.
 *
 * @param {string} eventType The type of events to query; either a standard
 * event type (`traces`, `customEvents`, `pageViews`, `requests`,
 * `dependencies`, `exceptions`, `availabilityResults`) or `$all` to query
 * across all event types. Possible values include: '$all', 'traces',
 * 'customEvents', 'pageViews', 'browserTimings', 'requests', 'dependencies',
 * 'exceptions', 'availabilityResults', 'performanceCounters', 'customMetrics'
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {string} [options.timespan] Optional. The timespan over which to
 * retrieve events. This is an ISO8601 time period value.  This timespan is
 * applied in addition to any that are specified in the Odata expression.
 *
 * @param {string} [options.filter] An expression used to filter the returned
 * events
 *
 * @param {string} [options.search] A free-text search expression to match for
 * whether a particular event should be returned
 *
 * @param {string} [options.orderby] A comma-separated list of properties with
 * \"asc\" (the default) or \"desc\" to control the order of returned events
 *
 * @param {string} [options.select] Limits the properties to just those
 * requested on each returned event
 *
 * @param {number} [options.skip] The number of items to skip over before
 * returning events
 *
 * @param {number} [options.top] The number of events to return
 *
 * @param {string} [options.format] Format for the returned events
 *
 * @param {boolean} [options.count] Request a count of matching items included
 * with the returned events
 *
 * @param {string} [options.apply] An expression used for aggregation over
 * returned events
 *
 * @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 EventsResults} 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 _getByType(appId, eventType, 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 filter = (options && options.filter !== undefined) ? options.filter : undefined;
  let search = (options && options.search !== undefined) ? options.search : undefined;
  let orderby = (options && options.orderby !== undefined) ? options.orderby : undefined;
  let select = (options && options.select !== undefined) ? options.select : undefined;
  let skip = (options && options.skip !== undefined) ? options.skip : undefined;
  let top = (options && options.top !== undefined) ? options.top : undefined;
  let format = (options && options.format !== undefined) ? options.format : undefined;
  let count = (options && options.count !== undefined) ? options.count : undefined;
  let apply = (options && options.apply !== undefined) ? options.apply : 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 (eventType === null || eventType === undefined || typeof eventType.valueOf() !== 'string') {
      throw new Error('eventType 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 (filter !== null && filter !== undefined && typeof filter.valueOf() !== 'string') {
      throw new Error('filter must be of type string.');
    }
    if (search !== null && search !== undefined && typeof search.valueOf() !== 'string') {
      throw new Error('search must be of type string.');
    }
    if (orderby !== null && orderby !== undefined && typeof orderby.valueOf() !== 'string') {
      throw new Error('orderby must be of type string.');
    }
    if (select !== null && select !== undefined && typeof select.valueOf() !== 'string') {
      throw new Error('select must be of type string.');
    }
    if (skip !== null && skip !== undefined && typeof skip !== 'number') {
      throw new Error('skip must be of type number.');
    }
    if (top !== null && top !== undefined && typeof top !== 'number') {
      throw new Error('top must be of type number.');
    }
    if (format !== null && format !== undefined && typeof format.valueOf() !== 'string') {
      throw new Error('format must be of type string.');
    }
    if (count !== null && count !== undefined && typeof count !== 'boolean') {
      throw new Error('count must be of type boolean.');
    }
    if (apply !== null && apply !== undefined && typeof apply.valueOf() !== 'string') {
      throw new Error('apply must be of type string.');
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  let baseUrl = this.client.baseUri;
  let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'apps/{appId}/events/{eventType}';
  requestUrl = requestUrl.replace('{appId}', encodeURIComponent(appId));
  requestUrl = requestUrl.replace('{eventType}', encodeURIComponent(eventType));
  let queryParameters = [];
  if (timespan !== null && timespan !== undefined) {
    queryParameters.push('timespan=' + encodeURIComponent(timespan));
  }
  if (filter !== null && filter !== undefined) {
    queryParameters.push('$filter=' + encodeURIComponent(filter));
  }
  if (search !== null && search !== undefined) {
    queryParameters.push('$search=' + encodeURIComponent(search));
  }
  if (orderby !== null && orderby !== undefined) {
    queryParameters.push('$orderby=' + encodeURIComponent(orderby));
  }
  if (select !== null && select !== undefined) {
    queryParameters.push('$select=' + encodeURIComponent(select));
  }
  if (skip !== null && skip !== undefined) {
    queryParameters.push('$skip=' + encodeURIComponent(skip.toString()));
  }
  if (top !== null && top !== undefined) {
    queryParameters.push('$top=' + encodeURIComponent(top.toString()));
  }
  if (format !== null && format !== undefined) {
    queryParameters.push('$format=' + encodeURIComponent(format));
  }
  if (count !== null && count !== undefined) {
    queryParameters.push('$count=' + encodeURIComponent(count.toString()));
  }
  if (apply !== null && apply !== undefined) {
    queryParameters.push('$apply=' + encodeURIComponent(apply));
  }
  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['EventsResults']().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 Get an event
 *
 * Gets the data for a single event
 *
 * @param {string} appId ID of the application. This is Application ID from the
 * API Access settings blade in the Azure portal.
 *
 * @param {string} eventType The type of events to query; either a standard
 * event type (`traces`, `customEvents`, `pageViews`, `requests`,
 * `dependencies`, `exceptions`, `availabilityResults`) or `$all` to query
 * across all event types. Possible values include: '$all', 'traces',
 * 'customEvents', 'pageViews', 'browserTimings', 'requests', 'dependencies',
 * 'exceptions', 'availabilityResults', 'performanceCounters', 'customMetrics'
 *
 * @param {string} eventId ID of event.
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {string} [options.timespan] Optional. The timespan over which to
 * retrieve events. This is an ISO8601 time period value.  This timespan is
 * applied in addition to any that are specified in the Odata expression.
 *
 * @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 EventsResults} 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, eventType, eventId, 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;
  // 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 (eventType === null || eventType === undefined || typeof eventType.valueOf() !== 'string') {
      throw new Error('eventType 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 (eventId === null || eventId === undefined || typeof eventId.valueOf() !== 'string') {
      throw new Error('eventId 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}/events/{eventType}/{eventId}';
  requestUrl = requestUrl.replace('{appId}', encodeURIComponent(appId));
  requestUrl = requestUrl.replace('{eventType}', encodeURIComponent(eventType));
  requestUrl = requestUrl.replace('{eventId}', encodeURIComponent(eventId));
  let queryParameters = [];
  if (timespan !== null && timespan !== undefined) {
    queryParameters.push('timespan=' + encodeURIComponent(timespan));
  }
  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['EventsResults']().mapper();
          result = client.deserialize(resultMapper, parsedResponse, 'result');
        }
      } catch (error) {
        let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`);
        deserializationError.request = msRest.stripRequest(httpRequest);
        deserializationError.response = msRest.stripResponse(response);
        return callback(deserializationError);
      }
    }

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

/** Class representing a Events. */
class Events {
  /**
   * Create a Events.
   * @param {ApplicationInsightsDataClient} client Reference to the service client.
   */
  constructor(client) {
    this.client = client;
    this._getByType = _getByType;
    this._get = _get;
  }

  /**
   * @summary Execute OData query
   *
   * Executes an OData query for events
   *
   * @param {string} appId ID of the application. This is Application ID from the
   * API Access settings blade in the Azure portal.
   *
   * @param {string} eventType The type of events to query; either a standard
   * event type (`traces`, `customEvents`, `pageViews`, `requests`,
   * `dependencies`, `exceptions`, `availabilityResults`) or `$all` to query
   * across all event types. Possible values include: '$all', 'traces',
   * 'customEvents', 'pageViews', 'browserTimings', 'requests', 'dependencies',
   * 'exceptions', 'availabilityResults', 'performanceCounters', 'customMetrics'
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {string} [options.timespan] Optional. The timespan over which to
   * retrieve events. This is an ISO8601 time period value.  This timespan is
   * applied in addition to any that are specified in the Odata expression.
   *
   * @param {string} [options.filter] An expression used to filter the returned
   * events
   *
   * @param {string} [options.search] A free-text search expression to match for
   * whether a particular event should be returned
   *
   * @param {string} [options.orderby] A comma-separated list of properties with
   * \"asc\" (the default) or \"desc\" to control the order of returned events
   *
   * @param {string} [options.select] Limits the properties to just those
   * requested on each returned event
   *
   * @param {number} [options.skip] The number of items to skip over before
   * returning events
   *
   * @param {number} [options.top] The number of events to return
   *
   * @param {string} [options.format] Format for the returned events
   *
   * @param {boolean} [options.count] Request a count of matching items included
   * with the returned events
   *
   * @param {string} [options.apply] An expression used for aggregation over
   * returned events
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<EventsResults>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  getByTypeWithHttpOperationResponse(appId, eventType, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._getByType(appId, eventType, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * @summary Execute OData query
   *
   * Executes an OData query for events
   *
   * @param {string} appId ID of the application. This is Application ID from the
   * API Access settings blade in the Azure portal.
   *
   * @param {string} eventType The type of events to query; either a standard
   * event type (`traces`, `customEvents`, `pageViews`, `requests`,
   * `dependencies`, `exceptions`, `availabilityResults`) or `$all` to query
   * across all event types. Possible values include: '$all', 'traces',
   * 'customEvents', 'pageViews', 'browserTimings', 'requests', 'dependencies',
   * 'exceptions', 'availabilityResults', 'performanceCounters', 'customMetrics'
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {string} [options.timespan] Optional. The timespan over which to
   * retrieve events. This is an ISO8601 time period value.  This timespan is
   * applied in addition to any that are specified in the Odata expression.
   *
   * @param {string} [options.filter] An expression used to filter the returned
   * events
   *
   * @param {string} [options.search] A free-text search expression to match for
   * whether a particular event should be returned
   *
   * @param {string} [options.orderby] A comma-separated list of properties with
   * \"asc\" (the default) or \"desc\" to control the order of returned events
   *
   * @param {string} [options.select] Limits the properties to just those
   * requested on each returned event
   *
   * @param {number} [options.skip] The number of items to skip over before
   * returning events
   *
   * @param {number} [options.top] The number of events to return
   *
   * @param {string} [options.format] Format for the returned events
   *
   * @param {boolean} [options.count] Request a count of matching items included
   * with the returned events
   *
   * @param {string} [options.apply] An expression used for aggregation over
   * returned events
   *
   * @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 {EventsResults} - 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 EventsResults} 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.
   */
  getByType(appId, eventType, 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._getByType(appId, eventType, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._getByType(appId, eventType, options, optionalCallback);
    }
  }

  /**
   * @summary Get an event
   *
   * Gets the data for a single event
   *
   * @param {string} appId ID of the application. This is Application ID from the
   * API Access settings blade in the Azure portal.
   *
   * @param {string} eventType The type of events to query; either a standard
   * event type (`traces`, `customEvents`, `pageViews`, `requests`,
   * `dependencies`, `exceptions`, `availabilityResults`) or `$all` to query
   * across all event types. Possible values include: '$all', 'traces',
   * 'customEvents', 'pageViews', 'browserTimings', 'requests', 'dependencies',
   * 'exceptions', 'availabilityResults', 'performanceCounters', 'customMetrics'
   *
   * @param {string} eventId ID of event.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {string} [options.timespan] Optional. The timespan over which to
   * retrieve events. This is an ISO8601 time period value.  This timespan is
   * applied in addition to any that are specified in the Odata expression.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<EventsResults>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  getWithHttpOperationResponse(appId, eventType, eventId, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._get(appId, eventType, eventId, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * @summary Get an event
   *
   * Gets the data for a single event
   *
   * @param {string} appId ID of the application. This is Application ID from the
   * API Access settings blade in the Azure portal.
   *
   * @param {string} eventType The type of events to query; either a standard
   * event type (`traces`, `customEvents`, `pageViews`, `requests`,
   * `dependencies`, `exceptions`, `availabilityResults`) or `$all` to query
   * across all event types. Possible values include: '$all', 'traces',
   * 'customEvents', 'pageViews', 'browserTimings', 'requests', 'dependencies',
   * 'exceptions', 'availabilityResults', 'performanceCounters', 'customMetrics'
   *
   * @param {string} eventId ID of event.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {string} [options.timespan] Optional. The timespan over which to
   * retrieve events. This is an ISO8601 time period value.  This timespan is
   * applied in addition to any that are specified in the Odata expression.
   *
   * @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 {EventsResults} - 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 EventsResults} 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, eventType, eventId, 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, eventType, eventId, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._get(appId, eventType, eventId, options, optionalCallback);
    }
  }

}

module.exports = Events;
