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

// 
// Copyright (c) Microsoft and contributors.  All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// 
// See the License for the specific language governing permissions and
// limitations under the License.
// 

// Warning: This code was generated by a tool.
// 
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.

'use strict';

var util = require('util');
var azureCommon = require('azure-common');
var Service = azureCommon.Service;
var WebResource = azureCommon.WebResource;

var UsageAggregationManagementClient = ( /** @lends UsageAggregationManagementClient */ function() {
  /**
   * @class
   * Initializes a new instance of the UsageAggregationManagementClient class.
   * @constructor
   * 
   * @param {SubscriptionCloudCredentials} credentials Gets subscription
   * credentials which uniquely identify Microsoft Azure subscription. The
   * subscription ID forms part of the URI for every service call.
   * 
   * @param {string} [credentials.subscriptionId]
   * 
   * @param {string} [baseUri] Gets the URI used as the base for all cloud
   * service requests.
   * 
   * @param {Array} filters
   */
  function UsageAggregationManagementClient(credentials, baseUri, filters) {
    if (credentials === null || credentials === undefined) {
      throw new Error('credentials cannot be null.');
    }
    
    UsageAggregationManagementClient['super_'].call(this, credentials, filters);
    
    this.credentials = credentials;
    this.baseUri = baseUri;
    if (this.baseUri === null || this.baseUri === undefined) {
      this.baseUri = 'https://management.azure.com';
    }
    if (this.apiVersion === null || this.apiVersion === undefined) {
      this.apiVersion = '2015-06-01-preview';
    }
    if (this.longRunningOperationInitialTimeout === null || this.longRunningOperationInitialTimeout === undefined) {
      this.longRunningOperationInitialTimeout = -1;
    }
    if (this.longRunningOperationRetryTimeout === null || this.longRunningOperationRetryTimeout === undefined) {
      this.longRunningOperationRetryTimeout = -1;
    }
    /**
     * Provides an instance of the
     * [UsageAggregationOperations](-UsageAggregationOperations.html) object.
     * @type {object}
     */
    this.usageAggregates = new UsageAggregationOperations(this);
  }
  
  util.inherits(UsageAggregationManagementClient, Service);
  
  
  return UsageAggregationManagementClient;
})();
exports.UsageAggregationManagementClient = UsageAggregationManagementClient;

var UsageAggregationOperations = ( /** @lends UsageAggregationOperations */ function() {
  /**
   * @class
   * __NOTE__: An instance of this class is automatically created for an
   * instance of the [UsageAggregationManagementClient] {@link
   * UsageAggregationManagementClient~UsageAggregationManagementClient}.
   * See [usageAggregates] {@link
   * UsageAggregationManagementClient~UsageAggregationManagementClient#usageAggregates}.
   * Initializes a new instance of the UsageAggregationOperations class.
   * @constructor
   * 
   * @param {UsageAggregationManagementClient} client Reference to the service
   * client.
   */
  function UsageAggregationOperations(client) {
    this.client = client;
  }
  
  /**
   * Query aggregated Azure subscription consumption data for a date range.
   * (see
   * https://msdn.microsoft.com/library/azure/1ea5b323-54bb-423d-916f-190de96c6a3c
   * for more information)
   * 
   * @param {Date} reportedStartTime The start of the time range to retrieve
   * data for.
   * 
   * @param {Date} reportedEndTime The end of the time range to retrieve data
   * for.
   * 
   * @param {AggregationGranularity} [aggregationGranularity] Value is either
   * daily (default) or hourly to tell the API how to return the results
   * grouped by day or hour.
   * 
   * @param {boolean} [showDetails] When set to true (default), the aggregates
   * are broken down into the instance metadata which is more granular.
   * 
   * @param {string} [continuationToken] Retrieved from previous calls, this is
   * the bookmark used for progress when the responses are paged.
   * 
   * @param {function} callback
   * 
   * @returns {Stream} The response stream.
   */
  UsageAggregationOperations.prototype.get = function(reportedStartTime, reportedEndTime, aggregationGranularity, showDetails, continuationToken, callback) {
    if (callback === null || callback === undefined) {
      throw new Error('callback cannot be null.');
    }
    // Validate
    if (reportedStartTime === null || reportedStartTime === undefined) {
      return callback(new Error('reportedStartTime cannot be null.'));
    }
    if (isNaN(Date.parse(reportedStartTime))) {
      return callback(new Error('reportedStartTime is not a valid date'));
    }
    if (reportedEndTime === null || reportedEndTime === undefined) {
      return callback(new Error('reportedEndTime cannot be null.'));
    }
    if (isNaN(Date.parse(reportedEndTime))) {
      return callback(new Error('reportedEndTime is not a valid date'));
    }
        
    // Tracing
    
    // Construct URL
    var url2 = '';
    url2 = url2 + 'subscriptions/';
    if (this.client.credentials.subscriptionId !== null && this.client.credentials.subscriptionId !== undefined) {
      url2 = url2 + encodeURIComponent(this.client.credentials.subscriptionId);
    }
    url2 = url2 + '/providers/Microsoft.Commerce/UsageAggregates';
    var queryParameters = [];
    queryParameters.push('api-version=2015-06-01-preview');
    queryParameters.push('reportedstartTime=' + encodeURIComponent(reportedStartTime));
    queryParameters.push('reportedEndTime=' + encodeURIComponent(reportedEndTime));
    if (showDetails !== null && showDetails !== undefined) {
      queryParameters.push('showDetails=' + encodeURIComponent(showDetails.toString()));
    }
    if (aggregationGranularity !== null && aggregationGranularity !== undefined) {
      queryParameters.push('aggregationGranularity=' + encodeURIComponent(aggregationGranularity !== null && aggregationGranularity !== undefined ? aggregationGranularity.toString() : 'Daily'));
    }
    if (continuationToken !== null && continuationToken !== undefined) {
      queryParameters.push('continuationToken=' + encodeURIComponent(continuationToken));
    }
    if (queryParameters.length > 0) {
      url2 = url2 + '?' + queryParameters.join('&');
    }
    var baseUrl = this.client.baseUri;
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl[baseUrl.length - 1] === '/') {
      baseUrl = baseUrl.substring(0, (baseUrl.length - 1) + 0);
    }
    if (url2[0] === '/') {
      url2 = url2.substring(1);
    }
    url2 = baseUrl + '/' + url2;
    url2 = url2.replace(' ', '%20');
    
    // Create HTTP transport objects
    var httpRequest = new WebResource();
    httpRequest.method = 'GET';
    httpRequest.headers = {};
    httpRequest.url = url2;
    
    // Set Headers
  
    // Send Request
    return this.client.pipeline(httpRequest, function (err, response, body) {
      if (err !== null && err !== undefined) {
        return callback(err);
      }
      var statusCode = response.statusCode;
      if (statusCode !== 200) {
        var error = new Error(body);
        error.statusCode = response.statusCode;
        return callback(error);
      }

      // Create Result
      var result = null;
      // Deserialize Response
      if (statusCode === 200) {
        var responseContent = body;
        result = { usageAggregations: [] };
        var responseDoc = null;
        if (responseContent) {
          responseDoc = JSON.parse(responseContent);
        }
        
        if (responseDoc !== null && responseDoc !== undefined) {
          var valueArray = responseDoc['value'];
          if (valueArray !== null && valueArray !== undefined) {
            for (var loweredIndex1 = 0; loweredIndex1 < valueArray.length; loweredIndex1 = loweredIndex1 + 1) {
              var valueValue = valueArray[loweredIndex1];
              var usageAggregationInstance = {};
              result.usageAggregations.push(usageAggregationInstance);
              
              var idValue = valueValue['id'];
              if (idValue !== null && idValue !== undefined) {
                var idInstance = idValue;
                usageAggregationInstance.id = idInstance;
              }
              
              var nameValue = valueValue['name'];
              if (nameValue !== null && nameValue !== undefined) {
                var nameInstance = nameValue;
                usageAggregationInstance.name = nameInstance;
              }
              
              var typeValue = valueValue['type'];
              if (typeValue !== null && typeValue !== undefined) {
                var typeInstance = typeValue;
                usageAggregationInstance.type = typeInstance;
              }
              
              var propertiesValue = valueValue['properties'];
              if (propertiesValue !== null && propertiesValue !== undefined) {
                var propertiesInstance = {};
                usageAggregationInstance.properties = propertiesInstance;
                
                var meterIdValue = propertiesValue['meterId'];
                if (meterIdValue !== null && meterIdValue !== undefined) {
                  var meterIdInstance = meterIdValue;
                  propertiesInstance.meterId = meterIdInstance;
                }
                
                var usageStartTimeValue = propertiesValue['usageStartTime'];
                if (usageStartTimeValue !== null && usageStartTimeValue !== undefined) {
                  var usageStartTimeInstance = usageStartTimeValue;
                  propertiesInstance.usageStartTime = usageStartTimeInstance;
                }
                
                var usageEndTimeValue = propertiesValue['usageEndTime'];
                if (usageEndTimeValue !== null && usageEndTimeValue !== undefined) {
                  var usageEndTimeInstance = usageEndTimeValue;
                  propertiesInstance.usageEndTime = usageEndTimeInstance;
                }
                
                var quantityValue = propertiesValue['quantity'];
                if (quantityValue !== null && quantityValue !== undefined) {
                  var quantityInstance = quantityValue;
                  propertiesInstance.quantity = quantityInstance;
                }
                
                var unitValue = propertiesValue['unit'];
                if (unitValue !== null && unitValue !== undefined) {
                  var unitInstance = unitValue;
                  propertiesInstance.unit = unitInstance;
                }
                
                var meterNameValue = propertiesValue['meterName'];
                if (meterNameValue !== null && meterNameValue !== undefined) {
                  var meterNameInstance = meterNameValue;
                  propertiesInstance.meterName = meterNameInstance;
                }
                
                var meterCategoryValue = propertiesValue['meterCategory'];
                if (meterCategoryValue !== null && meterCategoryValue !== undefined) {
                  var meterCategoryInstance = meterCategoryValue;
                  propertiesInstance.meterCategory = meterCategoryInstance;
                }
                
                var meterSubCategoryValue = propertiesValue['meterSubCategory'];
                if (meterSubCategoryValue !== null && meterSubCategoryValue !== undefined) {
                  var meterSubCategoryInstance = meterSubCategoryValue;
                  propertiesInstance.meterSubCategory = meterSubCategoryInstance;
                }
                
                var meterRegionValue = propertiesValue['meterRegion'];
                if (meterRegionValue !== null && meterRegionValue !== undefined) {
                  var meterRegionInstance = meterRegionValue;
                  propertiesInstance.meterRegion = meterRegionInstance;
                }
                
                var infoFieldsValue = propertiesValue['infoFields'];
                if (infoFieldsValue !== null && infoFieldsValue !== undefined) {
                  var infoFieldsInstance = {};
                  propertiesInstance.infoFields = infoFieldsInstance;
                  
                  var projectValue = infoFieldsValue['project'];
                  if (projectValue !== null && projectValue !== undefined) {
                    var projectInstance = projectValue;
                    infoFieldsInstance.project = projectInstance;
                  }
                }
                
                var instanceDataValue = propertiesValue['instanceData'];
                if (instanceDataValue !== null && instanceDataValue !== undefined) {
                  var instanceDataInstance = instanceDataValue;
                  propertiesInstance.instanceData = instanceDataInstance;
                }
              }
            }
          }
          
          var nextLinkValue = responseDoc['nextLink'];
          if (nextLinkValue !== null && nextLinkValue !== undefined) {
            var nextLinkInstance = nextLinkValue;
            result.nextLink = nextLinkInstance;
          }
        }
        
      }
      result.statusCode = statusCode;
      
      return callback(null, result);
    });
  };
  
  return UsageAggregationOperations;
})();
