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

var util = require('util');
var msRest = require('ms-rest');
var msRestAzure = require('ms-rest-azure');
var WebResource = msRest.WebResource;

/**
 * @class
 * FormulaOperations
 * __NOTE__: An instance of this class is automatically created for an
 * instance of the DevTestLabsClient.
 * Initializes a new instance of the FormulaOperations class.
 * @constructor
 *
 * @param {DevTestLabsClient} client Reference to the service client.
 */
function FormulaOperations(client) {
  this.client = client;
}

/**
 * List formulas.
 *
 * @param {string} resourceGroupName The name of the resource group.
 * 
 * @param {string} labName The name of the lab.
 * 
 * @param {object} [options] Optional Parameters.
 * 
 * @param {string} [options.filter] The filter to apply on the operation.
 * 
 * @param {number} [options.top]
 * 
 * @param {string} [options.orderBy]
 * 
 * @param {object} [options.customHeaders] Headers that will be added to the
 * request
 * 
 * @param {function} 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.
 *                      See {@link ResponseWithContinuationFormula} 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.
 */
FormulaOperations.prototype.list = function (resourceGroupName, labName, options, callback) {
  var client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }
  var filter = (options && options.filter !== undefined) ? options.filter : undefined;
  var top = (options && options.top !== undefined) ? options.top : undefined;
  var orderBy = (options && options.orderBy !== undefined) ? options.orderBy : undefined;
  // Validate
  try {
    if (this.client.subscriptionId === null || this.client.subscriptionId === undefined || typeof this.client.subscriptionId.valueOf() !== 'string') {
      throw new Error('this.client.subscriptionId cannot be null or undefined and it must be of type string.');
    }
    if (resourceGroupName === null || resourceGroupName === undefined || typeof resourceGroupName.valueOf() !== 'string') {
      throw new Error('resourceGroupName cannot be null or undefined and it must be of type string.');
    }
    if (labName === null || labName === undefined || typeof labName.valueOf() !== 'string') {
      throw new Error('labName cannot be null or undefined and it must be of type string.');
    }
    if (filter !== null && filter !== undefined && typeof filter.valueOf() !== 'string') {
      throw new Error('filter must be of type string.');
    }
    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 (this.client.apiVersion === null || this.client.apiVersion === undefined || typeof this.client.apiVersion.valueOf() !== 'string') {
      throw new Error('this.client.apiVersion cannot be null or undefined and it must be of type string.');
    }
    if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
      throw new Error('this.client.acceptLanguage must be of type string.');
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  var requestUrl = this.client.baseUri +
                   '//subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/formulas';
  requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
  requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
  requestUrl = requestUrl.replace('{labName}', encodeURIComponent(labName));
  var queryParameters = [];
  if (filter !== null && filter !== undefined) {
    queryParameters.push('$filter=' + encodeURIComponent(filter));
  }
  if (top !== null && top !== undefined) {
    queryParameters.push('$top=' + encodeURIComponent(top.toString()));
  }
  if (orderBy !== null && orderBy !== undefined) {
    queryParameters.push('$orderBy=' + encodeURIComponent(orderBy));
  }
  queryParameters.push('api-version=' + encodeURIComponent(this.client.apiVersion));
  if (queryParameters.length > 0) {
    requestUrl += '?' + queryParameters.join('&');
  }
  // trim all duplicate forward slashes in the url
  var regex = /([^:]\/)\/+/gi;
  requestUrl = requestUrl.replace(regex, '$1');

  // Create HTTP transport objects
  var httpRequest = new WebResource();
  httpRequest.method = 'GET';
  httpRequest.headers = {};
  httpRequest.url = requestUrl;
  // Set Headers
  if (this.client.generateClientRequestId) {
      httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if(options) {
    for(var headerName in options['customHeaders']) {
      if (options['customHeaders'].hasOwnProperty(headerName)) {
        httpRequest.headers[headerName] = options['customHeaders'][headerName];
      }
    }
  }
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  httpRequest.body = null;
  // Send Request
  return client.pipeline(httpRequest, function (err, response, responseBody) {
    if (err) {
      return callback(err);
    }
    var statusCode = response.statusCode;
    if (statusCode !== 200) {
      var error = new Error(responseBody);
      error.statusCode = response.statusCode;
      error.request = msRest.stripRequest(httpRequest);
      error.response = msRest.stripResponse(response);
      if (responseBody === '') responseBody = null;
      var parsedErrorResponse;
      try {
        parsedErrorResponse = JSON.parse(responseBody);
        if (parsedErrorResponse) {
          if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
          if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
          if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          var resultMapper = new client.models['CloudError']().mapper();
          error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
        }
      } catch (defaultError) {
        error.message = util.format('Error "%s" occurred in deserializing the responseBody ' + 
                         '- "%s" for the default response.', defaultError.message, responseBody);
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    var result = null;
    if (responseBody === '') responseBody = null;
    // Deserialize Response
    if (statusCode === 200) {
      var parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          var resultMapper = new client.models['ResponseWithContinuationFormula']().mapper();
          result = client.deserialize(resultMapper, parsedResponse, 'result');
        }
      } catch (error) {
        var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody));
        deserializationError.request = msRest.stripRequest(httpRequest);
        deserializationError.response = msRest.stripResponse(response);
        return callback(deserializationError);
      }
    }

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

/**
 * Get formula.
 *
 * @param {string} resourceGroupName The name of the resource group.
 * 
 * @param {string} labName The name of the lab.
 * 
 * @param {string} name The name of the formula.
 * 
 * @param {object} [options] Optional Parameters.
 * 
 * @param {object} [options.customHeaders] Headers that will be added to the
 * request
 * 
 * @param {function} 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.
 *                      See {@link Formula} 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.
 */
FormulaOperations.prototype.getResource = function (resourceGroupName, labName, name, options, callback) {
  var client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }
  // Validate
  try {
    if (this.client.subscriptionId === null || this.client.subscriptionId === undefined || typeof this.client.subscriptionId.valueOf() !== 'string') {
      throw new Error('this.client.subscriptionId cannot be null or undefined and it must be of type string.');
    }
    if (resourceGroupName === null || resourceGroupName === undefined || typeof resourceGroupName.valueOf() !== 'string') {
      throw new Error('resourceGroupName cannot be null or undefined and it must be of type string.');
    }
    if (labName === null || labName === undefined || typeof labName.valueOf() !== 'string') {
      throw new Error('labName cannot be null or undefined and it must be of type string.');
    }
    if (name === null || name === undefined || typeof name.valueOf() !== 'string') {
      throw new Error('name cannot be null or undefined and it must be of type string.');
    }
    if (this.client.apiVersion === null || this.client.apiVersion === undefined || typeof this.client.apiVersion.valueOf() !== 'string') {
      throw new Error('this.client.apiVersion cannot be null or undefined and it must be of type string.');
    }
    if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
      throw new Error('this.client.acceptLanguage must be of type string.');
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  var requestUrl = this.client.baseUri +
                   '//subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/formulas/{name}';
  requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
  requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
  requestUrl = requestUrl.replace('{labName}', encodeURIComponent(labName));
  requestUrl = requestUrl.replace('{name}', encodeURIComponent(name));
  var queryParameters = [];
  queryParameters.push('api-version=' + encodeURIComponent(this.client.apiVersion));
  if (queryParameters.length > 0) {
    requestUrl += '?' + queryParameters.join('&');
  }
  // trim all duplicate forward slashes in the url
  var regex = /([^:]\/)\/+/gi;
  requestUrl = requestUrl.replace(regex, '$1');

  // Create HTTP transport objects
  var httpRequest = new WebResource();
  httpRequest.method = 'GET';
  httpRequest.headers = {};
  httpRequest.url = requestUrl;
  // Set Headers
  if (this.client.generateClientRequestId) {
      httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if(options) {
    for(var headerName in options['customHeaders']) {
      if (options['customHeaders'].hasOwnProperty(headerName)) {
        httpRequest.headers[headerName] = options['customHeaders'][headerName];
      }
    }
  }
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  httpRequest.body = null;
  // Send Request
  return client.pipeline(httpRequest, function (err, response, responseBody) {
    if (err) {
      return callback(err);
    }
    var statusCode = response.statusCode;
    if (statusCode !== 200) {
      var error = new Error(responseBody);
      error.statusCode = response.statusCode;
      error.request = msRest.stripRequest(httpRequest);
      error.response = msRest.stripResponse(response);
      if (responseBody === '') responseBody = null;
      var parsedErrorResponse;
      try {
        parsedErrorResponse = JSON.parse(responseBody);
        if (parsedErrorResponse) {
          if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
          if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
          if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          var resultMapper = new client.models['CloudError']().mapper();
          error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
        }
      } catch (defaultError) {
        error.message = util.format('Error "%s" occurred in deserializing the responseBody ' + 
                         '- "%s" for the default response.', defaultError.message, responseBody);
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    var result = null;
    if (responseBody === '') responseBody = null;
    // Deserialize Response
    if (statusCode === 200) {
      var parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          var resultMapper = new client.models['Formula']().mapper();
          result = client.deserialize(resultMapper, parsedResponse, 'result');
        }
      } catch (error) {
        var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody));
        deserializationError.request = msRest.stripRequest(httpRequest);
        deserializationError.response = msRest.stripResponse(response);
        return callback(deserializationError);
      }
    }

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

/**
 *
 * Create or replace an existing Formula. This operation can take a while to
 * complete.
 *
 * @param {string} resourceGroupName The name of the resource group.
 * 
 * @param {string} labName The name of the lab.
 * 
 * @param {string} name The name of the formula.
 * 
 * @param {object} formula
 * 
 * @param {string} [formula.description] The description of the formula.
 * 
 * @param {string} [formula.author] The author of the formula.
 * 
 * @param {string} [formula.osType] The OS type of the formula.
 * 
 * @param {date} [formula.creationDate] The creation date of the formula.
 * 
 * @param {object} [formula.formulaContent] The content of the formula.
 * 
 * @param {string} [formula.formulaContent.notes] The notes of the virtual
 * machine.
 * 
 * @param {string} [formula.formulaContent.ownerObjectId] The object
 * identifier of the owner of the virtual machine.
 * 
 * @param {string} [formula.formulaContent.createdByUserId] The object
 * identifier of the creator of the virtual machine.
 * 
 * @param {string} [formula.formulaContent.createdByUser] The email address of
 * creator of the virtual machine.
 * 
 * @param {string} [formula.formulaContent.computeId] The resource identifier
 * (Microsoft.Compute) of the virtual machine.
 * 
 * @param {string} [formula.formulaContent.customImageId] The custom image
 * identifier of the virtual machine.
 * 
 * @param {string} [formula.formulaContent.osType] The OS type of the virtual
 * machine.
 * 
 * @param {string} [formula.formulaContent.size] The size of the virtual
 * machine.
 * 
 * @param {string} [formula.formulaContent.userName] The user name of the
 * virtual machine.
 * 
 * @param {string} [formula.formulaContent.password] The password of the
 * virtual machine administrator.
 * 
 * @param {string} [formula.formulaContent.sshKey] The SSH key of the virtual
 * machine administrator.
 * 
 * @param {boolean} [formula.formulaContent.isAuthenticationWithSshKey] A
 * value indicating whether this virtual machine uses an SSH key for
 * authentication.
 * 
 * @param {string} [formula.formulaContent.fqdn] The fully-qualified domain
 * name of the virtual machine.
 * 
 * @param {string} [formula.formulaContent.labSubnetName] The lab subnet name
 * of the virtual machine.
 * 
 * @param {string} [formula.formulaContent.labVirtualNetworkId] The lab
 * virtual network identifier of the virtual machine.
 * 
 * @param {boolean} [formula.formulaContent.disallowPublicIpAddress] Indicates
 * whether the virtual machine is to be created without a public IP address.
 * 
 * @param {array} [formula.formulaContent.artifacts] The artifacts to be
 * installed on the virtual machine.
 * 
 * @param {object} [formula.formulaContent.artifactDeploymentStatus] The
 * artifact deployment status for the virtual machine.
 * 
 * @param {string}
 * [formula.formulaContent.artifactDeploymentStatus.deploymentStatus] The
 * deployment status of the artifact.
 * 
 * @param {number}
 * [formula.formulaContent.artifactDeploymentStatus.artifactsApplied] The
 * total count of the artifacts that were successfully applied.
 * 
 * @param {number}
 * [formula.formulaContent.artifactDeploymentStatus.totalArtifacts] The total
 * count of the artifacts that were tentatively applied.
 * 
 * @param {object} [formula.formulaContent.galleryImageReference] The
 * Microsoft Azure Marketplace image reference of the virtual machine.
 * 
 * @param {string} [formula.formulaContent.galleryImageReference.offer] The
 * offer of the gallery image.
 * 
 * @param {string} [formula.formulaContent.galleryImageReference.publisher]
 * The publisher of the gallery image.
 * 
 * @param {string} [formula.formulaContent.galleryImageReference.sku] The SKU
 * of the gallery image.
 * 
 * @param {string} [formula.formulaContent.galleryImageReference.osType] The
 * OS type of the gallery image.
 * 
 * @param {string} [formula.formulaContent.galleryImageReference.version] The
 * version of the gallery image.
 * 
 * @param {string} [formula.formulaContent.provisioningState] The provisioning
 * status of the resource.
 * 
 * @param {string} [formula.formulaContent.id] The identifier of the resource.
 * 
 * @param {string} [formula.formulaContent.name] The name of the resource.
 * 
 * @param {string} [formula.formulaContent.type] The type of the resource.
 * 
 * @param {string} [formula.formulaContent.location] The location of the
 * resource.
 * 
 * @param {object} [formula.formulaContent.tags] The tags of the resource.
 * 
 * @param {object} [formula.vm] Information about a VM from which a formula is
 * to be created.
 * 
 * @param {string} [formula.vm.labVmId] The identifier of the VM from which a
 * formula is to be created.
 * 
 * @param {string} [formula.provisioningState] The provisioning status of the
 * resource.
 * 
 * @param {string} [formula.id] The identifier of the resource.
 * 
 * @param {string} [formula.name] The name of the resource.
 * 
 * @param {string} [formula.type] The type of the resource.
 * 
 * @param {string} [formula.location] The location of the resource.
 * 
 * @param {object} [formula.tags] The tags of the resource.
 * 
 * @param {object} [options] Optional Parameters.
 * 
 * @param {object} [options.customHeaders] Headers that will be added to the
 * request
 * 
 * @param {function} 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.
 *                      See {@link Formula} 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.
 */
FormulaOperations.prototype.createOrUpdateResource = function (resourceGroupName, labName, name, formula, options, callback) {
  var client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }

  if (!callback) {
    throw new Error('callback cannot be null.');
  }

  // Send request
  this.beginCreateOrUpdateResource(resourceGroupName, labName, name, formula, options, function (err, parsedResult, httpRequest, response){
    if (err) return callback(err);

    var initialResult = new msRest.HttpOperationResponse();
    initialResult.request = httpRequest;
    initialResult.response = response;
    initialResult.body = response.body;
    client.getLongRunningOperationResult(initialResult, options, function (err, pollingResult) {
      if (err) return callback(err);

      // Create Result
      var result = null;
      httpRequest = pollingResult.request;
      response = pollingResult.response;
      var responseBody = pollingResult.body;
      if (responseBody === '') responseBody = null;

      // Deserialize Response
      var parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          var resultMapper = new client.models['Formula']().mapper();
          result = client.deserialize(resultMapper, parsedResponse, 'result');
        }
      } catch (error) {
        var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody));
        deserializationError.request = msRest.stripRequest(httpRequest);
        deserializationError.response = msRest.stripResponse(response);
        return callback(deserializationError);
      }

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

/**
 * Create or replace an existing Formula. This operation can take a while to
 * complete.
 *
 * @param {string} resourceGroupName The name of the resource group.
 * 
 * @param {string} labName The name of the lab.
 * 
 * @param {string} name The name of the formula.
 * 
 * @param {object} formula
 * 
 * @param {string} [formula.description] The description of the formula.
 * 
 * @param {string} [formula.author] The author of the formula.
 * 
 * @param {string} [formula.osType] The OS type of the formula.
 * 
 * @param {date} [formula.creationDate] The creation date of the formula.
 * 
 * @param {object} [formula.formulaContent] The content of the formula.
 * 
 * @param {string} [formula.formulaContent.notes] The notes of the virtual
 * machine.
 * 
 * @param {string} [formula.formulaContent.ownerObjectId] The object
 * identifier of the owner of the virtual machine.
 * 
 * @param {string} [formula.formulaContent.createdByUserId] The object
 * identifier of the creator of the virtual machine.
 * 
 * @param {string} [formula.formulaContent.createdByUser] The email address of
 * creator of the virtual machine.
 * 
 * @param {string} [formula.formulaContent.computeId] The resource identifier
 * (Microsoft.Compute) of the virtual machine.
 * 
 * @param {string} [formula.formulaContent.customImageId] The custom image
 * identifier of the virtual machine.
 * 
 * @param {string} [formula.formulaContent.osType] The OS type of the virtual
 * machine.
 * 
 * @param {string} [formula.formulaContent.size] The size of the virtual
 * machine.
 * 
 * @param {string} [formula.formulaContent.userName] The user name of the
 * virtual machine.
 * 
 * @param {string} [formula.formulaContent.password] The password of the
 * virtual machine administrator.
 * 
 * @param {string} [formula.formulaContent.sshKey] The SSH key of the virtual
 * machine administrator.
 * 
 * @param {boolean} [formula.formulaContent.isAuthenticationWithSshKey] A
 * value indicating whether this virtual machine uses an SSH key for
 * authentication.
 * 
 * @param {string} [formula.formulaContent.fqdn] The fully-qualified domain
 * name of the virtual machine.
 * 
 * @param {string} [formula.formulaContent.labSubnetName] The lab subnet name
 * of the virtual machine.
 * 
 * @param {string} [formula.formulaContent.labVirtualNetworkId] The lab
 * virtual network identifier of the virtual machine.
 * 
 * @param {boolean} [formula.formulaContent.disallowPublicIpAddress] Indicates
 * whether the virtual machine is to be created without a public IP address.
 * 
 * @param {array} [formula.formulaContent.artifacts] The artifacts to be
 * installed on the virtual machine.
 * 
 * @param {object} [formula.formulaContent.artifactDeploymentStatus] The
 * artifact deployment status for the virtual machine.
 * 
 * @param {string}
 * [formula.formulaContent.artifactDeploymentStatus.deploymentStatus] The
 * deployment status of the artifact.
 * 
 * @param {number}
 * [formula.formulaContent.artifactDeploymentStatus.artifactsApplied] The
 * total count of the artifacts that were successfully applied.
 * 
 * @param {number}
 * [formula.formulaContent.artifactDeploymentStatus.totalArtifacts] The total
 * count of the artifacts that were tentatively applied.
 * 
 * @param {object} [formula.formulaContent.galleryImageReference] The
 * Microsoft Azure Marketplace image reference of the virtual machine.
 * 
 * @param {string} [formula.formulaContent.galleryImageReference.offer] The
 * offer of the gallery image.
 * 
 * @param {string} [formula.formulaContent.galleryImageReference.publisher]
 * The publisher of the gallery image.
 * 
 * @param {string} [formula.formulaContent.galleryImageReference.sku] The SKU
 * of the gallery image.
 * 
 * @param {string} [formula.formulaContent.galleryImageReference.osType] The
 * OS type of the gallery image.
 * 
 * @param {string} [formula.formulaContent.galleryImageReference.version] The
 * version of the gallery image.
 * 
 * @param {string} [formula.formulaContent.provisioningState] The provisioning
 * status of the resource.
 * 
 * @param {string} [formula.formulaContent.id] The identifier of the resource.
 * 
 * @param {string} [formula.formulaContent.name] The name of the resource.
 * 
 * @param {string} [formula.formulaContent.type] The type of the resource.
 * 
 * @param {string} [formula.formulaContent.location] The location of the
 * resource.
 * 
 * @param {object} [formula.formulaContent.tags] The tags of the resource.
 * 
 * @param {object} [formula.vm] Information about a VM from which a formula is
 * to be created.
 * 
 * @param {string} [formula.vm.labVmId] The identifier of the VM from which a
 * formula is to be created.
 * 
 * @param {string} [formula.provisioningState] The provisioning status of the
 * resource.
 * 
 * @param {string} [formula.id] The identifier of the resource.
 * 
 * @param {string} [formula.name] The name of the resource.
 * 
 * @param {string} [formula.type] The type of the resource.
 * 
 * @param {string} [formula.location] The location of the resource.
 * 
 * @param {object} [formula.tags] The tags of the resource.
 * 
 * @param {object} [options] Optional Parameters.
 * 
 * @param {object} [options.customHeaders] Headers that will be added to the
 * request
 * 
 * @param {function} 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.
 *                      See {@link Formula} 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.
 */
FormulaOperations.prototype.beginCreateOrUpdateResource = function (resourceGroupName, labName, name, formula, options, callback) {
  var client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }
  // Validate
  try {
    if (this.client.subscriptionId === null || this.client.subscriptionId === undefined || typeof this.client.subscriptionId.valueOf() !== 'string') {
      throw new Error('this.client.subscriptionId cannot be null or undefined and it must be of type string.');
    }
    if (resourceGroupName === null || resourceGroupName === undefined || typeof resourceGroupName.valueOf() !== 'string') {
      throw new Error('resourceGroupName cannot be null or undefined and it must be of type string.');
    }
    if (labName === null || labName === undefined || typeof labName.valueOf() !== 'string') {
      throw new Error('labName cannot be null or undefined and it must be of type string.');
    }
    if (name === null || name === undefined || typeof name.valueOf() !== 'string') {
      throw new Error('name cannot be null or undefined and it must be of type string.');
    }
    if (formula === null || formula === undefined) {
      throw new Error('formula cannot be null or undefined.');
    }
    if (this.client.apiVersion === null || this.client.apiVersion === undefined || typeof this.client.apiVersion.valueOf() !== 'string') {
      throw new Error('this.client.apiVersion cannot be null or undefined and it must be of type string.');
    }
    if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
      throw new Error('this.client.acceptLanguage must be of type string.');
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  var requestUrl = this.client.baseUri +
                   '//subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/formulas/{name}';
  requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
  requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
  requestUrl = requestUrl.replace('{labName}', encodeURIComponent(labName));
  requestUrl = requestUrl.replace('{name}', encodeURIComponent(name));
  var queryParameters = [];
  queryParameters.push('api-version=' + encodeURIComponent(this.client.apiVersion));
  if (queryParameters.length > 0) {
    requestUrl += '?' + queryParameters.join('&');
  }
  // trim all duplicate forward slashes in the url
  var regex = /([^:]\/)\/+/gi;
  requestUrl = requestUrl.replace(regex, '$1');

  // Create HTTP transport objects
  var httpRequest = new WebResource();
  httpRequest.method = 'PUT';
  httpRequest.headers = {};
  httpRequest.url = requestUrl;
  // Set Headers
  if (this.client.generateClientRequestId) {
      httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if(options) {
    for(var headerName in options['customHeaders']) {
      if (options['customHeaders'].hasOwnProperty(headerName)) {
        httpRequest.headers[headerName] = options['customHeaders'][headerName];
      }
    }
  }
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  // Serialize Request
  var requestContent = null;
  var requestModel = null;
  try {
    if (formula !== null && formula !== undefined) {
      var requestModelMapper = new client.models['Formula']().mapper();
      requestModel = client.serialize(requestModelMapper, formula, 'formula');
      requestContent = JSON.stringify(requestModel);
    }
  } catch (error) {
    var serializationError = new Error(util.format('Error "%s" occurred in serializing the ' + 
        'payload - "%s"', error.message, util.inspect(formula, {depth: null})));
    return callback(serializationError);
  }
  httpRequest.body = requestContent;
  // Send Request
  return client.pipeline(httpRequest, function (err, response, responseBody) {
    if (err) {
      return callback(err);
    }
    var statusCode = response.statusCode;
    if (statusCode !== 200 && statusCode !== 201) {
      var error = new Error(responseBody);
      error.statusCode = response.statusCode;
      error.request = msRest.stripRequest(httpRequest);
      error.response = msRest.stripResponse(response);
      if (responseBody === '') responseBody = null;
      var parsedErrorResponse;
      try {
        parsedErrorResponse = JSON.parse(responseBody);
        if (parsedErrorResponse) {
          if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
          if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
          if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          var resultMapper = new client.models['CloudError']().mapper();
          error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
        }
      } catch (defaultError) {
        error.message = util.format('Error "%s" occurred in deserializing the responseBody ' + 
                         '- "%s" for the default response.', defaultError.message, responseBody);
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    var result = null;
    if (responseBody === '') responseBody = null;
    // Deserialize Response
    if (statusCode === 200) {
      var parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          var resultMapper = new client.models['Formula']().mapper();
          result = client.deserialize(resultMapper, parsedResponse, 'result');
        }
      } catch (error) {
        var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody));
        deserializationError.request = msRest.stripRequest(httpRequest);
        deserializationError.response = msRest.stripResponse(response);
        return callback(deserializationError);
      }
    }
    // Deserialize Response
    if (statusCode === 201) {
      var parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          var resultMapper = new client.models['Formula']().mapper();
          result = client.deserialize(resultMapper, parsedResponse, 'result');
        }
      } catch (error) {
        var deserializationError1 = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody));
        deserializationError1.request = msRest.stripRequest(httpRequest);
        deserializationError1.response = msRest.stripResponse(response);
        return callback(deserializationError1);
      }
    }

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

/**
 * Delete formula.
 *
 * @param {string} resourceGroupName The name of the resource group.
 * 
 * @param {string} labName The name of the lab.
 * 
 * @param {string} name The name of the formula.
 * 
 * @param {object} [options] Optional Parameters.
 * 
 * @param {object} [options.customHeaders] Headers that will be added to the
 * request
 * 
 * @param {function} callback
 *
 * @returns {function} callback(err, result, request, response)
 *
 *                      {Error}  err        - The Error object if an error occurred, null otherwise.
 *
 *                      {null} [result]   - The deserialized result object.
 *
 *                      {object} [request]  - The HTTP Request object if an error did not occur.
 *
 *                      {stream} [response] - The HTTP Response stream if an error did not occur.
 */
FormulaOperations.prototype.deleteResource = function (resourceGroupName, labName, name, options, callback) {
  var client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }
  // Validate
  try {
    if (this.client.subscriptionId === null || this.client.subscriptionId === undefined || typeof this.client.subscriptionId.valueOf() !== 'string') {
      throw new Error('this.client.subscriptionId cannot be null or undefined and it must be of type string.');
    }
    if (resourceGroupName === null || resourceGroupName === undefined || typeof resourceGroupName.valueOf() !== 'string') {
      throw new Error('resourceGroupName cannot be null or undefined and it must be of type string.');
    }
    if (labName === null || labName === undefined || typeof labName.valueOf() !== 'string') {
      throw new Error('labName cannot be null or undefined and it must be of type string.');
    }
    if (name === null || name === undefined || typeof name.valueOf() !== 'string') {
      throw new Error('name cannot be null or undefined and it must be of type string.');
    }
    if (this.client.apiVersion === null || this.client.apiVersion === undefined || typeof this.client.apiVersion.valueOf() !== 'string') {
      throw new Error('this.client.apiVersion cannot be null or undefined and it must be of type string.');
    }
    if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
      throw new Error('this.client.acceptLanguage must be of type string.');
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  var requestUrl = this.client.baseUri +
                   '//subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/formulas/{name}';
  requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
  requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
  requestUrl = requestUrl.replace('{labName}', encodeURIComponent(labName));
  requestUrl = requestUrl.replace('{name}', encodeURIComponent(name));
  var queryParameters = [];
  queryParameters.push('api-version=' + encodeURIComponent(this.client.apiVersion));
  if (queryParameters.length > 0) {
    requestUrl += '?' + queryParameters.join('&');
  }
  // trim all duplicate forward slashes in the url
  var regex = /([^:]\/)\/+/gi;
  requestUrl = requestUrl.replace(regex, '$1');

  // Create HTTP transport objects
  var httpRequest = new WebResource();
  httpRequest.method = 'DELETE';
  httpRequest.headers = {};
  httpRequest.url = requestUrl;
  // Set Headers
  if (this.client.generateClientRequestId) {
      httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if(options) {
    for(var headerName in options['customHeaders']) {
      if (options['customHeaders'].hasOwnProperty(headerName)) {
        httpRequest.headers[headerName] = options['customHeaders'][headerName];
      }
    }
  }
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  httpRequest.body = null;
  // Send Request
  return client.pipeline(httpRequest, function (err, response, responseBody) {
    if (err) {
      return callback(err);
    }
    var statusCode = response.statusCode;
    if (statusCode !== 200 && statusCode !== 204) {
      var error = new Error(responseBody);
      error.statusCode = response.statusCode;
      error.request = msRest.stripRequest(httpRequest);
      error.response = msRest.stripResponse(response);
      if (responseBody === '') responseBody = null;
      var parsedErrorResponse;
      try {
        parsedErrorResponse = JSON.parse(responseBody);
        if (parsedErrorResponse) {
          if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
          if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
          if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          var resultMapper = new client.models['CloudError']().mapper();
          error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
        }
      } catch (defaultError) {
        error.message = util.format('Error "%s" occurred in deserializing the responseBody ' + 
                         '- "%s" for the default response.', defaultError.message, responseBody);
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    var result = null;
    if (responseBody === '') responseBody = null;

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

/**
 * List formulas.
 *
 * @param {string} nextPageLink The NextLink from the previous successful call
 * to List operation.
 * 
 * @param {object} [options] Optional Parameters.
 * 
 * @param {object} [options.customHeaders] Headers that will be added to the
 * request
 * 
 * @param {function} 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.
 *                      See {@link ResponseWithContinuationFormula} 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.
 */
FormulaOperations.prototype.listNext = function (nextPageLink, options, callback) {
  var client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }
  // Validate
  try {
    if (nextPageLink === null || nextPageLink === undefined || typeof nextPageLink.valueOf() !== 'string') {
      throw new Error('nextPageLink cannot be null or undefined and it must be of type string.');
    }
    if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
      throw new Error('this.client.acceptLanguage must be of type string.');
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  var requestUrl = '{nextLink}';
  requestUrl = requestUrl.replace('{nextLink}', nextPageLink);
  // trim all duplicate forward slashes in the url
  var regex = /([^:]\/)\/+/gi;
  requestUrl = requestUrl.replace(regex, '$1');

  // Create HTTP transport objects
  var httpRequest = new WebResource();
  httpRequest.method = 'GET';
  httpRequest.headers = {};
  httpRequest.url = requestUrl;
  // Set Headers
  if (this.client.generateClientRequestId) {
      httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if(options) {
    for(var headerName in options['customHeaders']) {
      if (options['customHeaders'].hasOwnProperty(headerName)) {
        httpRequest.headers[headerName] = options['customHeaders'][headerName];
      }
    }
  }
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  httpRequest.body = null;
  // Send Request
  return client.pipeline(httpRequest, function (err, response, responseBody) {
    if (err) {
      return callback(err);
    }
    var statusCode = response.statusCode;
    if (statusCode !== 200) {
      var error = new Error(responseBody);
      error.statusCode = response.statusCode;
      error.request = msRest.stripRequest(httpRequest);
      error.response = msRest.stripResponse(response);
      if (responseBody === '') responseBody = null;
      var parsedErrorResponse;
      try {
        parsedErrorResponse = JSON.parse(responseBody);
        if (parsedErrorResponse) {
          if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
          if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
          if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          var resultMapper = new client.models['CloudError']().mapper();
          error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
        }
      } catch (defaultError) {
        error.message = util.format('Error "%s" occurred in deserializing the responseBody ' + 
                         '- "%s" for the default response.', defaultError.message, responseBody);
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    var result = null;
    if (responseBody === '') responseBody = null;
    // Deserialize Response
    if (statusCode === 200) {
      var parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          var resultMapper = new client.models['ResponseWithContinuationFormula']().mapper();
          result = client.deserialize(resultMapper, parsedResponse, 'result');
        }
      } catch (error) {
        var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody));
        deserializationError.request = msRest.stripRequest(httpRequest);
        deserializationError.response = msRest.stripResponse(response);
        return callback(deserializationError);
      }
    }

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


module.exports = FormulaOperations;
