/* 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 moment = require('moment');
var azureCommon = require('azure-common');
var Service = azureCommon.Service;
var WebResource = azureCommon.WebResource;

var AlertsClient = ( /** @lends AlertsClient */ function() {
  /**
   * @class
   * Initializes a new instance of the AlertsClient 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 AlertsClient(credentials, baseUri, filters) {
    if (credentials === null || credentials === undefined) {
      throw new Error('credentials cannot be null.');
    }
    
    AlertsClient['super_'].call(this, credentials, filters);
    
    this.credentials = credentials;
    this.baseUri = baseUri;
    if (this.baseUri === null || this.baseUri === undefined) {
      this.baseUri = 'https://management.core.windows.net';
    }
    if (this.apiVersion === null || this.apiVersion === undefined) {
      this.apiVersion = '2013-10-01';
    }
    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
     * [IncidentOperations](-IncidentOperations.html) object.
     * @type {object}
     */
    this.incidents = new IncidentOperations(this);
    /**
     * Provides an instance of the [RuleOperations](-RuleOperations.html)
     * object.
     * @type {object}
     */
    this.rules = new RuleOperations(this);
  }
  
  util.inherits(AlertsClient, Service);
  
  
  return AlertsClient;
})();
exports.AlertsClient = AlertsClient;

var IncidentOperations = ( /** @lends IncidentOperations */ function() {
  /**
   * @class
   * Operations for managing the alert incidents.
   * __NOTE__: An instance of this class is automatically created for an
   * instance of the [AlertsClient] {@link AlertsClient~AlertsClient}.
   * See [incidents] {@link AlertsClient~AlertsClient#incidents}.
   * Initializes a new instance of the IncidentOperations class.
   * @constructor
   * 
   * @param {AlertsClient} client Reference to the service client.
   */
  function IncidentOperations(client) {
    this.client = client;
  }
  
  /**
   * 
   * @param {string} incidentId The id of the incident to retrieve.
   * 
   * @param {function} callback
   * 
   * @returns {Stream} The response stream.
   */
  IncidentOperations.prototype.get = function(incidentId, callback) {
    if (callback === null || callback === undefined) {
      throw new Error('callback cannot be null.');
    }
    // Validate
    if (incidentId === null || incidentId === undefined) {
      return callback(new Error('incidentId cannot be null.'));
    }
    
    // Tracing
    
    // Construct URL
    var url2 = '';
    url2 = url2 + '/';
    if (this.client.credentials.subscriptionId !== null && this.client.credentials.subscriptionId !== undefined) {
      url2 = url2 + encodeURIComponent(this.client.credentials.subscriptionId);
    }
    url2 = url2 + '/services/monitoring/alertincidents/';
    url2 = url2 + encodeURIComponent(incidentId);
    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
    httpRequest.headers['Accept'] = 'application/json';
    httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
    httpRequest.headers['x-ms-version'] = '2013-10-01';
    
    // 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 = {};
        var responseDoc = null;
        if (responseContent) {
          responseDoc = JSON.parse(responseContent);
        }
        
        if (responseDoc !== null && responseDoc !== undefined) {
          var incidentInstance = {};
          result.incident = incidentInstance;
          
          var idValue = responseDoc['Id'];
          if (idValue !== null && idValue !== undefined) {
            var idInstance = idValue;
            incidentInstance.id = idInstance;
          }
          
          var ruleIdValue = responseDoc['RuleId'];
          if (ruleIdValue !== null && ruleIdValue !== undefined) {
            var ruleIdInstance = ruleIdValue;
            incidentInstance.ruleId = ruleIdInstance;
          }
          
          var isActiveValue = responseDoc['IsActive'];
          if (isActiveValue !== null && isActiveValue !== undefined) {
            var isActiveInstance = isActiveValue;
            incidentInstance.isActive = isActiveInstance;
          }
          
          var activatedTimeValue = responseDoc['ActivatedTime'];
          if (activatedTimeValue !== null && activatedTimeValue !== undefined) {
            var activatedTimeInstance = activatedTimeValue;
            incidentInstance.activatedTime = activatedTimeInstance;
          }
          
          var resolvedTimeValue = responseDoc['ResolvedTime'];
          if (resolvedTimeValue !== null && resolvedTimeValue !== undefined) {
            var resolvedTimeInstance = resolvedTimeValue;
            incidentInstance.resolvedTime = resolvedTimeInstance;
          }
        }
        
      }
      result.statusCode = statusCode;
      result.requestId = response.headers['x-ms-request-id'];
      
      return callback(null, result);
    });
  };
  
  /**
   * 
   * @param {function} callback
   * 
   * @returns {Stream} The response stream.
   */
  IncidentOperations.prototype.listActiveForSubscription = function(callback) {
    if (callback === null || callback === undefined) {
      throw new Error('callback cannot be null.');
    }
    // Validate
    
    // Tracing
    
    // Construct URL
    var url2 = '';
    url2 = url2 + '/';
    if (this.client.credentials.subscriptionId !== null && this.client.credentials.subscriptionId !== undefined) {
      url2 = url2 + encodeURIComponent(this.client.credentials.subscriptionId);
    }
    url2 = url2 + '/services/monitoring/alertincidents';
    var queryParameters = [];
    var odataFilter = [];
    odataFilter.push('IsActive eq true');
    if (odataFilter.length > 0) {
      queryParameters.push('$filter=' + odataFilter.join(null));
    }
    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
    httpRequest.headers['Accept'] = 'application/json';
    httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
    httpRequest.headers['x-ms-version'] = '2013-10-01';
    
    // 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 = { value: [] };
        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 incidentInstance = {};
              result.value.push(incidentInstance);
              
              var idValue = valueValue['Id'];
              if (idValue !== null && idValue !== undefined) {
                var idInstance = idValue;
                incidentInstance.id = idInstance;
              }
              
              var ruleIdValue = valueValue['RuleId'];
              if (ruleIdValue !== null && ruleIdValue !== undefined) {
                var ruleIdInstance = ruleIdValue;
                incidentInstance.ruleId = ruleIdInstance;
              }
              
              var isActiveValue = valueValue['IsActive'];
              if (isActiveValue !== null && isActiveValue !== undefined) {
                var isActiveInstance = isActiveValue;
                incidentInstance.isActive = isActiveInstance;
              }
              
              var activatedTimeValue = valueValue['ActivatedTime'];
              if (activatedTimeValue !== null && activatedTimeValue !== undefined) {
                var activatedTimeInstance = activatedTimeValue;
                incidentInstance.activatedTime = activatedTimeInstance;
              }
              
              var resolvedTimeValue = valueValue['ResolvedTime'];
              if (resolvedTimeValue !== null && resolvedTimeValue !== undefined) {
                var resolvedTimeInstance = resolvedTimeValue;
                incidentInstance.resolvedTime = resolvedTimeInstance;
              }
            }
          }
        }
        
      }
      result.statusCode = statusCode;
      result.requestId = response.headers['x-ms-request-id'];
      
      return callback(null, result);
    });
  };
  
  /**
   * 
   * @param {string} ruleId The rule id.
   * 
   * @param {boolean} [isActive] A boolean to retrieve only active or resolved
   * incidents.
   * 
   * @param {function} callback
   * 
   * @returns {Stream} The response stream.
   */
  IncidentOperations.prototype.listForRule = function(ruleId, isActive, callback) {
    if (callback === null || callback === undefined) {
      throw new Error('callback cannot be null.');
    }
    // Validate
    if (ruleId === null || ruleId === undefined) {
      return callback(new Error('ruleId cannot be null.'));
    }
    
    // Tracing
    
    // Construct URL
    var url2 = '';
    url2 = url2 + '/';
    if (this.client.credentials.subscriptionId !== null && this.client.credentials.subscriptionId !== undefined) {
      url2 = url2 + encodeURIComponent(this.client.credentials.subscriptionId);
    }
    url2 = url2 + '/services/monitoring/alertrules/';
    url2 = url2 + encodeURIComponent(ruleId);
    url2 = url2 + '/alertincidents';
    var queryParameters = [];
    var odataFilter = [];
    if (isActive !== null && isActive !== undefined) {
      odataFilter.push('IsActive eq ' + encodeURIComponent(isActive.toString()));
    }
    if (odataFilter.length > 0) {
      queryParameters.push('$filter=' + odataFilter.join(null));
    }
    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
    httpRequest.headers['Accept'] = 'application/json';
    httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
    httpRequest.headers['x-ms-version'] = '2013-10-01';
    
    // 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 = { value: [] };
        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 incidentInstance = {};
              result.value.push(incidentInstance);
              
              var idValue = valueValue['Id'];
              if (idValue !== null && idValue !== undefined) {
                var idInstance = idValue;
                incidentInstance.id = idInstance;
              }
              
              var ruleIdValue = valueValue['RuleId'];
              if (ruleIdValue !== null && ruleIdValue !== undefined) {
                var ruleIdInstance = ruleIdValue;
                incidentInstance.ruleId = ruleIdInstance;
              }
              
              var isActiveValue = valueValue['IsActive'];
              if (isActiveValue !== null && isActiveValue !== undefined) {
                var isActiveInstance = isActiveValue;
                incidentInstance.isActive = isActiveInstance;
              }
              
              var activatedTimeValue = valueValue['ActivatedTime'];
              if (activatedTimeValue !== null && activatedTimeValue !== undefined) {
                var activatedTimeInstance = activatedTimeValue;
                incidentInstance.activatedTime = activatedTimeInstance;
              }
              
              var resolvedTimeValue = valueValue['ResolvedTime'];
              if (resolvedTimeValue !== null && resolvedTimeValue !== undefined) {
                var resolvedTimeInstance = resolvedTimeValue;
                incidentInstance.resolvedTime = resolvedTimeInstance;
              }
            }
          }
        }
        
      }
      result.statusCode = statusCode;
      result.requestId = response.headers['x-ms-request-id'];
      
      return callback(null, result);
    });
  };
  
  return IncidentOperations;
})();

var RuleOperations = ( /** @lends RuleOperations */ function() {
  /**
   * @class
   * Operations for managing the alert rules.
   * __NOTE__: An instance of this class is automatically created for an
   * instance of the [AlertsClient] {@link AlertsClient~AlertsClient}.
   * See [rules] {@link AlertsClient~AlertsClient#rules}.
   * Initializes a new instance of the RuleOperations class.
   * @constructor
   * 
   * @param {AlertsClient} client Reference to the service client.
   */
  function RuleOperations(client) {
    this.client = client;
  }
  
  /**
   * 
   * @param {RuleCreateOrUpdateParameters} parameters The rule to create or
   * update.
   * 
   * @param {Rule} [parameters.rule] The rule to create or update.
   * 
   * @param {string} [parameters.rule.id] Rule identifier.
   * 
   * @param {string} [parameters.rule.name] Rule name.
   * 
   * @param {string} [parameters.rule.description] Rule description.
   * 
   * @param {boolean} [parameters.rule.isEnabled] A flag that determines
   * whether the rule is enabled or disabled.
   * 
   * @param {RuleCondition} [parameters.rule.condition] Rule condition.
   * 
   * @param {array} [parameters.rule.actions] Rule actions.
   * 
   * @param {date} [parameters.rule.lastUpdatedTime] Rule last updated time.
   * 
   * @param {function} callback
   * 
   * @returns {Stream} The response stream.
   */
  RuleOperations.prototype.createOrUpdate = function(parameters, callback) {
    if (callback === null || callback === undefined) {
      throw new Error('callback cannot be null.');
    }
    // Validate
    if (parameters === null || parameters === undefined) {
      return callback(new Error('parameters cannot be null.'));
    }
    
    // Tracing
    
    // Construct URL
    var url2 = '';
    url2 = url2 + '/';
    if (this.client.credentials.subscriptionId !== null && this.client.credentials.subscriptionId !== undefined) {
      url2 = url2 + encodeURIComponent(this.client.credentials.subscriptionId);
    }
    url2 = url2 + '/services/monitoring/alertrules/';
    if (parameters.rule !== null && parameters.rule !== undefined && parameters.rule.id !== null && parameters.rule.id !== undefined) {
      url2 = url2 + encodeURIComponent(parameters.rule.id);
    }
    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 = 'PUT';
    httpRequest.headers = {};
    httpRequest.url = url2;
    
    // Set Headers
    httpRequest.headers['Accept'] = 'application/json';
    httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
    httpRequest.headers['x-ms-version'] = '2013-10-01';
    
    // Serialize Request
    var requestContent = null;
    var requestDoc = null;
    
    var ruleCreateOrUpdateParametersValue = {};
    requestDoc = ruleCreateOrUpdateParametersValue;
    
    if (parameters.rule !== null && parameters.rule !== undefined) {
      if (parameters.rule.id !== null && parameters.rule.id !== undefined) {
        ruleCreateOrUpdateParametersValue['Id'] = parameters.rule.id;
      }
      
      if (parameters.rule.name !== null && parameters.rule.name !== undefined) {
        ruleCreateOrUpdateParametersValue['Name'] = parameters.rule.name;
      }
      
      if (parameters.rule.description !== null && parameters.rule.description !== undefined) {
        ruleCreateOrUpdateParametersValue['Description'] = parameters.rule.description;
      }
      
      if (parameters.rule.isEnabled !== null && parameters.rule.isEnabled !== undefined) {
        ruleCreateOrUpdateParametersValue['IsEnabled'] = parameters.rule.isEnabled;
      }
      
      if (parameters.rule.condition !== null && parameters.rule.condition !== undefined) {
        var conditionValue = {};
        ruleCreateOrUpdateParametersValue['Condition'] = conditionValue;
        if (parameters.rule.condition.type === 'Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.ThresholdRuleCondition') {
          conditionValue['odata.type'] = parameters.rule.condition.type;
          var derived = parameters.rule.condition;
          
          if (derived.dataSource !== null && derived.dataSource !== undefined) {
            var dataSourceValue = {};
            conditionValue['DataSource'] = dataSourceValue;
            if (derived.dataSource.type === 'Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.RuleMetricDataSource') {
              dataSourceValue['odata.type'] = derived.dataSource.type;
              var derived2 = derived.dataSource;
              
              if (derived2.resourceId !== null && derived2.resourceId !== undefined) {
                dataSourceValue['ResourceId'] = derived2.resourceId;
              }
              
              if (derived2.metricNamespace !== null && derived2.metricNamespace !== undefined) {
                dataSourceValue['MetricNamespace'] = derived2.metricNamespace;
              }
              
              if (derived2.metricName !== null && derived2.metricName !== undefined) {
                dataSourceValue['MetricName'] = derived2.metricName;
              }
            }
          }
          
          if (derived.operator !== null && derived.operator !== undefined) {
            conditionValue['Operator'] = derived.operator !== null && derived.operator !== undefined ? derived.operator.toString() : 'GreaterThan';
          }
          
          if (derived.threshold !== null && derived.threshold !== undefined) {
            conditionValue['Threshold'] = derived.threshold;
          }
          
          if (derived.windowSize !== null && derived.windowSize !== undefined) {
            conditionValue['WindowSize'] = derived.windowSize.toIsoString();
          }
        }
      }
      
      if (parameters.rule.actions !== null && parameters.rule.actions !== undefined) {
        var actionsArray = [];
        for (var loweredIndex1 = 0; loweredIndex1 < parameters.rule.actions.length; loweredIndex1 = loweredIndex1 + 1) {
          var actionsItem = parameters.rule.actions[loweredIndex1];
          var ruleActionValue = {};
          actionsArray.push(ruleActionValue);
          if (actionsItem.type === 'Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.RuleEmailAction') {
            ruleActionValue['odata.type'] = actionsItem.type;
            var derived3 = actionsItem;
            
            if (derived3.sendToServiceOwners !== null && derived3.sendToServiceOwners !== undefined) {
              ruleActionValue['SendToServiceOwners'] = derived3.sendToServiceOwners;
            }
            
            if (derived3.customEmails !== null && derived3.customEmails !== undefined) {
              var customEmailsArray = [];
              for (var loweredIndex2 = 0; loweredIndex2 < derived3.customEmails.length; loweredIndex2 = loweredIndex2 + 1) {
                var customEmailsItem = derived3.customEmails[loweredIndex2];
                customEmailsArray.push(customEmailsItem);
              }
              ruleActionValue['CustomEmails'] = customEmailsArray;
            }
          }
        }
        ruleCreateOrUpdateParametersValue['Actions'] = actionsArray;
      }
      
      if (parameters.rule.lastUpdatedTime !== null && parameters.rule.lastUpdatedTime !== undefined) {
        ruleCreateOrUpdateParametersValue['LastUpdatedTime'] = parameters.rule.lastUpdatedTime;
      }
    }
    
    requestContent = JSON.stringify(requestDoc);
    httpRequest.body = requestContent;
    httpRequest.headers['Content-Length'] = Buffer.isBuffer(requestContent) ? requestContent.length : Buffer.byteLength(requestContent, 'UTF8');
    // 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 && statusCode !== 201) {
        var error = new Error(body);
        error.statusCode = response.statusCode;
        return callback(error);
      }
      
      // Create Result
      var result = null;
      // Deserialize Response
      if (statusCode === 200 || statusCode === 201) {
        var responseContent = body;
        result = {};
        var responseDoc = null;
        if (responseContent) {
          responseDoc = JSON.parse(responseContent);
        }
        
        if (responseDoc !== null && responseDoc !== undefined) {
        }
        
      }
      result.statusCode = statusCode;
      result.requestId = response.headers['x-ms-request-id'];
      
      return callback(null, result);
    });
  };
  
  /**
   * 
   * @param {string} ruleId The id of the rule to delete.
   * 
   * @param {function} callback
   * 
   * @returns {Stream} The response stream.
   */
  RuleOperations.prototype.deleteMethod = function(ruleId, callback) {
    if (callback === null || callback === undefined) {
      throw new Error('callback cannot be null.');
    }
    // Validate
    if (ruleId === null || ruleId === undefined) {
      return callback(new Error('ruleId cannot be null.'));
    }
    
    // Tracing
    
    // Construct URL
    var url2 = '';
    url2 = url2 + '/';
    if (this.client.credentials.subscriptionId !== null && this.client.credentials.subscriptionId !== undefined) {
      url2 = url2 + encodeURIComponent(this.client.credentials.subscriptionId);
    }
    url2 = url2 + '/services/monitoring/alertrules/';
    url2 = url2 + encodeURIComponent(ruleId);
    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 = 'DELETE';
    httpRequest.headers = {};
    httpRequest.url = url2;
    
    // Set Headers
    httpRequest.headers['Accept'] = 'application/json';
    httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
    httpRequest.headers['x-ms-version'] = '2013-10-01';
    
    // 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 = {};
        var responseDoc = null;
        if (responseContent) {
          responseDoc = JSON.parse(responseContent);
        }
        
        if (responseDoc !== null && responseDoc !== undefined) {
        }
        
      }
      result.statusCode = statusCode;
      result.requestId = response.headers['x-ms-request-id'];
      
      return callback(null, result);
    });
  };
  
  /**
   * 
   * @param {string} ruleId The id of the rule to retrieve.
   * 
   * @param {function} callback
   * 
   * @returns {Stream} The response stream.
   */
  RuleOperations.prototype.get = function(ruleId, callback) {
    if (callback === null || callback === undefined) {
      throw new Error('callback cannot be null.');
    }
    // Validate
    if (ruleId === null || ruleId === undefined) {
      return callback(new Error('ruleId cannot be null.'));
    }
    
    // Tracing
    
    // Construct URL
    var url2 = '';
    url2 = url2 + '/';
    if (this.client.credentials.subscriptionId !== null && this.client.credentials.subscriptionId !== undefined) {
      url2 = url2 + encodeURIComponent(this.client.credentials.subscriptionId);
    }
    url2 = url2 + '/services/monitoring/alertrules/';
    url2 = url2 + encodeURIComponent(ruleId);
    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
    httpRequest.headers['Accept'] = 'application/json';
    httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
    httpRequest.headers['x-ms-version'] = '2013-10-01';
    
    // 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 = {};
        var responseDoc = null;
        if (responseContent) {
          responseDoc = JSON.parse(responseContent);
        }
        
        if (responseDoc !== null && responseDoc !== undefined) {
          var ruleInstance = { actions: [] };
          result.rule = ruleInstance;
          
          var idValue = responseDoc['Id'];
          if (idValue !== null && idValue !== undefined) {
            var idInstance = idValue;
            ruleInstance.id = idInstance;
          }
          
          var nameValue = responseDoc['Name'];
          if (nameValue !== null && nameValue !== undefined) {
            var nameInstance = nameValue;
            ruleInstance.name = nameInstance;
          }
          
          var descriptionValue = responseDoc['Description'];
          if (descriptionValue !== null && descriptionValue !== undefined) {
            var descriptionInstance = descriptionValue;
            ruleInstance.description = descriptionInstance;
          }
          
          var isEnabledValue = responseDoc['IsEnabled'];
          if (isEnabledValue !== null && isEnabledValue !== undefined) {
            var isEnabledInstance = isEnabledValue;
            ruleInstance.isEnabled = isEnabledInstance;
          }
          
          var conditionValue = responseDoc['Condition'];
          if (conditionValue !== null && conditionValue !== undefined) {
            var typeName = conditionValue['odata.type'];
            if (typeName === 'Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.ThresholdRuleCondition') {
              var thresholdRuleConditionInstance = {};
              
              var dataSourceValue = conditionValue['DataSource'];
              if (dataSourceValue !== null && dataSourceValue !== undefined) {
                var typeName2 = dataSourceValue['odata.type'];
                if (typeName2 === 'Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.RuleMetricDataSource') {
                  var ruleMetricDataSourceInstance = {};
                  
                  var resourceIdValue = dataSourceValue['ResourceId'];
                  if (resourceIdValue !== null && resourceIdValue !== undefined) {
                    var resourceIdInstance = resourceIdValue;
                    ruleMetricDataSourceInstance.resourceId = resourceIdInstance;
                  }
                  
                  var metricNamespaceValue = dataSourceValue['MetricNamespace'];
                  if (metricNamespaceValue !== null && metricNamespaceValue !== undefined) {
                    var metricNamespaceInstance = metricNamespaceValue;
                    ruleMetricDataSourceInstance.metricNamespace = metricNamespaceInstance;
                  }
                  
                  var metricNameValue = dataSourceValue['MetricName'];
                  if (metricNameValue !== null && metricNameValue !== undefined) {
                    var metricNameInstance = metricNameValue;
                    ruleMetricDataSourceInstance.metricName = metricNameInstance;
                  }
                  thresholdRuleConditionInstance.dataSource = ruleMetricDataSourceInstance;
                }
              }
              
              var operatorValue = conditionValue['Operator'];
              if (operatorValue !== null && operatorValue !== undefined) {
                var operatorInstance = operatorValue;
                thresholdRuleConditionInstance.operator = operatorInstance;
              }
              
              var thresholdValue = conditionValue['Threshold'];
              if (thresholdValue !== null && thresholdValue !== undefined) {
                var thresholdInstance = thresholdValue;
                thresholdRuleConditionInstance.threshold = thresholdInstance;
              }
              
              var windowSizeValue = conditionValue['WindowSize'];
              if (windowSizeValue !== null && windowSizeValue !== undefined) {
                var windowSizeInstance = moment.duration(windowSizeValue);
                thresholdRuleConditionInstance.windowSize = windowSizeInstance;
              }
              ruleInstance.condition = thresholdRuleConditionInstance;
            }
          }
          
          var actionsArray = responseDoc['Actions'];
          if (actionsArray !== null && actionsArray !== undefined) {
            for (var loweredIndex1 = 0; loweredIndex1 < actionsArray.length; loweredIndex1 = loweredIndex1 + 1) {
              var actionsValue = actionsArray[loweredIndex1];
              var typeName3 = actionsValue['odata.type'];
              if (typeName3 === 'Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.RuleEmailAction') {
                var ruleEmailActionInstance = { customEmails: [] };
                
                var sendToServiceOwnersValue = actionsValue['SendToServiceOwners'];
                if (sendToServiceOwnersValue !== null && sendToServiceOwnersValue !== undefined) {
                  var sendToServiceOwnersInstance = sendToServiceOwnersValue;
                  ruleEmailActionInstance.sendToServiceOwners = sendToServiceOwnersInstance;
                }
                
                var customEmailsArray = actionsValue['CustomEmails'];
                if (customEmailsArray !== null && customEmailsArray !== undefined) {
                  for (var loweredIndex2 = 0; loweredIndex2 < customEmailsArray.length; loweredIndex2 = loweredIndex2 + 1) {
                    var customEmailsValue = customEmailsArray[loweredIndex2];
                    ruleEmailActionInstance.customEmails.push(customEmailsValue);
                  }
                }
                ruleInstance.actions.push(ruleEmailActionInstance);
              }
            }
          }
          
          var lastUpdatedTimeValue = responseDoc['LastUpdatedTime'];
          if (lastUpdatedTimeValue !== null && lastUpdatedTimeValue !== undefined) {
            var lastUpdatedTimeInstance = lastUpdatedTimeValue;
            ruleInstance.lastUpdatedTime = lastUpdatedTimeInstance;
          }
        }
        
      }
      result.statusCode = statusCode;
      result.requestId = response.headers['x-ms-request-id'];
      
      return callback(null, result);
    });
  };
  
  /**
   * List the alert rules within a subscription.
   * 
   * @param {function} callback
   * 
   * @returns {Stream} The response stream.
   */
  RuleOperations.prototype.list = function(callback) {
    if (callback === null || callback === undefined) {
      throw new Error('callback cannot be null.');
    }
    // Validate
    
    // Tracing
    
    // Construct URL
    var url2 = '';
    url2 = url2 + '/';
    if (this.client.credentials.subscriptionId !== null && this.client.credentials.subscriptionId !== undefined) {
      url2 = url2 + encodeURIComponent(this.client.credentials.subscriptionId);
    }
    url2 = url2 + '/services/monitoring/alertrules';
    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
    httpRequest.headers['Accept'] = 'application/json';
    httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
    httpRequest.headers['x-ms-version'] = '2013-10-01';
    
    // 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 = { value: [] };
        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 ruleInstance = { actions: [] };
              result.value.push(ruleInstance);
              
              var idValue = valueValue['Id'];
              if (idValue !== null && idValue !== undefined) {
                var idInstance = idValue;
                ruleInstance.id = idInstance;
              }
              
              var nameValue = valueValue['Name'];
              if (nameValue !== null && nameValue !== undefined) {
                var nameInstance = nameValue;
                ruleInstance.name = nameInstance;
              }
              
              var descriptionValue = valueValue['Description'];
              if (descriptionValue !== null && descriptionValue !== undefined) {
                var descriptionInstance = descriptionValue;
                ruleInstance.description = descriptionInstance;
              }
              
              var isEnabledValue = valueValue['IsEnabled'];
              if (isEnabledValue !== null && isEnabledValue !== undefined) {
                var isEnabledInstance = isEnabledValue;
                ruleInstance.isEnabled = isEnabledInstance;
              }
              
              var conditionValue = valueValue['Condition'];
              if (conditionValue !== null && conditionValue !== undefined) {
                var typeName = conditionValue['odata.type'];
                if (typeName === 'Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.ThresholdRuleCondition') {
                  var thresholdRuleConditionInstance = {};
                  
                  var dataSourceValue = conditionValue['DataSource'];
                  if (dataSourceValue !== null && dataSourceValue !== undefined) {
                    var typeName2 = dataSourceValue['odata.type'];
                    if (typeName2 === 'Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.RuleMetricDataSource') {
                      var ruleMetricDataSourceInstance = {};
                      
                      var resourceIdValue = dataSourceValue['ResourceId'];
                      if (resourceIdValue !== null && resourceIdValue !== undefined) {
                        var resourceIdInstance = resourceIdValue;
                        ruleMetricDataSourceInstance.resourceId = resourceIdInstance;
                      }
                      
                      var metricNamespaceValue = dataSourceValue['MetricNamespace'];
                      if (metricNamespaceValue !== null && metricNamespaceValue !== undefined) {
                        var metricNamespaceInstance = metricNamespaceValue;
                        ruleMetricDataSourceInstance.metricNamespace = metricNamespaceInstance;
                      }
                      
                      var metricNameValue = dataSourceValue['MetricName'];
                      if (metricNameValue !== null && metricNameValue !== undefined) {
                        var metricNameInstance = metricNameValue;
                        ruleMetricDataSourceInstance.metricName = metricNameInstance;
                      }
                      thresholdRuleConditionInstance.dataSource = ruleMetricDataSourceInstance;
                    }
                  }
                  
                  var operatorValue = conditionValue['Operator'];
                  if (operatorValue !== null && operatorValue !== undefined) {
                    var operatorInstance = operatorValue;
                    thresholdRuleConditionInstance.operator = operatorInstance;
                  }
                  
                  var thresholdValue = conditionValue['Threshold'];
                  if (thresholdValue !== null && thresholdValue !== undefined) {
                    var thresholdInstance = thresholdValue;
                    thresholdRuleConditionInstance.threshold = thresholdInstance;
                  }
                  
                  var windowSizeValue = conditionValue['WindowSize'];
                  if (windowSizeValue !== null && windowSizeValue !== undefined) {
                    var windowSizeInstance = moment.duration(windowSizeValue);
                    thresholdRuleConditionInstance.windowSize = windowSizeInstance;
                  }
                  ruleInstance.condition = thresholdRuleConditionInstance;
                }
              }
              
              var actionsArray = valueValue['Actions'];
              if (actionsArray !== null && actionsArray !== undefined) {
                for (var loweredIndex2 = 0; loweredIndex2 < actionsArray.length; loweredIndex2 = loweredIndex2 + 1) {
                  var actionsValue = actionsArray[loweredIndex2];
                  var typeName3 = actionsValue['odata.type'];
                  if (typeName3 === 'Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.RuleEmailAction') {
                    var ruleEmailActionInstance = { customEmails: [] };
                    
                    var sendToServiceOwnersValue = actionsValue['SendToServiceOwners'];
                    if (sendToServiceOwnersValue !== null && sendToServiceOwnersValue !== undefined) {
                      var sendToServiceOwnersInstance = sendToServiceOwnersValue;
                      ruleEmailActionInstance.sendToServiceOwners = sendToServiceOwnersInstance;
                    }
                    
                    var customEmailsArray = actionsValue['CustomEmails'];
                    if (customEmailsArray !== null && customEmailsArray !== undefined) {
                      for (var loweredIndex3 = 0; loweredIndex3 < customEmailsArray.length; loweredIndex3 = loweredIndex3 + 1) {
                        var customEmailsValue = customEmailsArray[loweredIndex3];
                        ruleEmailActionInstance.customEmails.push(customEmailsValue);
                      }
                    }
                    ruleInstance.actions.push(ruleEmailActionInstance);
                  }
                }
              }
              
              var lastUpdatedTimeValue = valueValue['LastUpdatedTime'];
              if (lastUpdatedTimeValue !== null && lastUpdatedTimeValue !== undefined) {
                var lastUpdatedTimeInstance = lastUpdatedTimeValue;
                ruleInstance.lastUpdatedTime = lastUpdatedTimeInstance;
              }
            }
          }
        }
        
      }
      result.statusCode = statusCode;
      result.requestId = response.headers['x-ms-request-id'];
      
      return callback(null, result);
    });
  };
  
  return RuleOperations;
})();
