/*
 * 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;
var moment = require('moment');

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

/**
 * @summary Adds a task to the specified job.
 *
 * @param {string} jobId The id of the job to which the task is to be added.
 * 
 * @param {object} task The task to be added.
 * 
 * @param {string} [task.id] A string that uniquely identifies the task within
 * the job. The id can contain any combination of alphanumeric characters
 * including hyphens and underscores, and cannot contain more than 64
 * characters. It is common to use a GUID for the id.
 * 
 * @param {string} [task.displayName] A display name for the task.
 * 
 * @param {string} [task.commandLine] The command line of the task. For
 * multi-instance tasks, the command line is executed on the primary subtask
 * after all the subtasks have finished executing the coordianation command
 * line. The command line does not run under a shell, and therefore cannot
 * take advantage of shell features such as environment variable expansion.
 * If you want to take advantage of such features, you should invoke the
 * shell in the command line, for example using "cmd /c MyCommand" in Windows
 * or "/bin/sh -c MyCommand" in Linux.
 * 
 * @param {object} [task.exitConditions] How the Batch service should respond
 * when the task completes.
 * 
 * @param {array} [task.exitConditions.exitCodes] A list of individual task
 * exit codes and how the Batch service should respond to them.
 * 
 * @param {array} [task.exitConditions.exitCodeRanges] A list of task exit
 * codes ranges and how the Batch service should respond to them.
 * 
 * @param {object} [task.exitConditions.schedulingError] How the Batch service
 * should respond if the task fails with a scheduling error.
 * 
 * @param {object} [task.exitConditions.default] How the Batch service should
 * respond if the task fails with an exit condition not covered by any of the
 * other properties – that is, any nonzero exit code not listed in the
 * exitCodes or exitCodeRanges collection, or a scheduling error if the
 * schedulingError property is not present.
 * 
 * @param {string} [task.exitConditions.default.jobAction] An action to take
 * on the job containing the task, if the task completes with the given exit
 * condition and the job’s onTaskFailed property is
 * 'performexitoptionsjobaction'. Possible values include: 'none', 'disable',
 * 'terminate'
 * 
 * @param {array} [task.resourceFiles] A list of files that the Batch service
 * will download to the compute node before running the command line. For
 * multi-instance tasks, the resource files will only be downloaded to the
 * compute node on which the primary subtask is executed.
 * 
 * @param {array} [task.environmentSettings] A list of environment variable
 * settings for the task.
 * 
 * @param {object} [task.affinityInfo] A locality hint that can be used by the
 * Batch service to select a compute node on which to start the new task.
 * 
 * @param {string} [task.affinityInfo.affinityId] An opaque string
 * representing the location of a compute node or a task that has run
 * previously. You can pass the affinityId of a compute node or task to
 * indicate that this task needs to be placed close to the node or task.
 * 
 * @param {object} [task.constraints] The execution constraints that apply to
 * this task.
 * 
 * @param {moment.duration} [task.constraints.maxWallClockTime] The maximum
 * elapsed time that the task may run, measured from the time the task
 * starts. If the task does not complete within the time limit, the Batch
 * service terminates it.
 * 
 * @param {moment.duration} [task.constraints.retentionTime] The minimum time
 * to retain the working directory for the task on the compute node where it
 * ran, from the time it completes execution. After this time, the Batch
 * service may delete the working directory and all its contents. The default
 * is infinite.
 * 
 * @param {number} [task.constraints.maxTaskRetryCount] The maximum number of
 * times the task may be retried. The Batch service retries a task if its
 * exit code is nonzero.
 * 
 * @param {boolean} [task.runElevated] Whether to run the task in elevated
 * mode.
 * 
 * @param {object} [task.multiInstanceSettings] Information about how to run
 * the multi-instance task.
 * 
 * @param {number} [task.multiInstanceSettings.numberOfInstances] The number
 * of compute nodes required by the multi-instance task.
 * 
 * @param {string} [task.multiInstanceSettings.coordinationCommandLine] The
 * command to run on the compute node instances for coordinating among the
 * subtasks.
 * 
 * @param {array} [task.multiInstanceSettings.commonResourceFiles] A list of
 * files that the Batch service will download before running the coordination
 * command line. The difference between common resource files and task
 * resource files is that common resource files are downloaded for all
 * subtasks including the primary, whereas task resource files are downloaded
 * only for the primary.
 * 
 * @param {object} [task.dependsOn] Any other tasks that this task depends on.
 * 
 * @param {array} [task.dependsOn.taskIds] The list of task ids that must
 * complete before this task can be scheduled.
 * 
 * @param {array} [task.dependsOn.taskIdRanges] The list of task ranges that
 * must complete before this task can be scheduled.
 * 
 * @param {array} [task.applicationPackageReferences] A list of application
 * packages that the Batch service will deploy to the compute node before
 * running the command line.
 * 
 * @param {object} [options] Optional Parameters.
 * 
 * @param {object} [options.taskAddOptions] Additional parameters for the
 * operation
 * 
 * @param {number} [options.taskAddOptions.timeout] The maximum time that the
 * server can spend processing the request, in seconds. The default is 30
 * seconds.
 * 
 * @param {string} [options.taskAddOptions.clientRequestId] The
 * caller-generated request identity, in the form of a GUID with no
 * decoration such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0.
 * 
 * @param {boolean} [options.taskAddOptions.returnClientRequestId] Whether the
 * server should return the client-request-id identifier in the response.
 * 
 * @param {date} [options.taskAddOptions.ocpDate] The time the request was
 * issued. If not specified, this header will be automatically populated with
 * the current system clock time.
 * 
 * @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.
 */
Task.prototype.add = function (jobId, task, 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 taskAddOptions = (options && options.taskAddOptions !== undefined) ? options.taskAddOptions : undefined;
  // Validate
  try {
    if (jobId === null || jobId === undefined || typeof jobId.valueOf() !== 'string') {
      throw new Error('jobId cannot be null or undefined and it must be of type string.');
    }
    if (task === null || task === undefined) {
      throw new Error('task 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);
  }
  var timeout;
  var clientRequestId;
  var returnClientRequestId;
  var ocpDate;
  try {
    if (taskAddOptions !== null && taskAddOptions !== undefined)
    {
      timeout = taskAddOptions.timeout;
      if (timeout !== null && timeout !== undefined && typeof timeout !== 'number') {
        throw new Error('timeout must be of type number.');
      }
    }
    if (taskAddOptions !== null && taskAddOptions !== undefined)
    {
      clientRequestId = taskAddOptions.clientRequestId;
      if (clientRequestId !== null && clientRequestId !== undefined && typeof clientRequestId.valueOf() !== 'string') {
        throw new Error('clientRequestId must be of type string.');
      }
    }
    if (taskAddOptions !== null && taskAddOptions !== undefined)
    {
      returnClientRequestId = taskAddOptions.returnClientRequestId;
      if (returnClientRequestId !== null && returnClientRequestId !== undefined && typeof returnClientRequestId !== 'boolean') {
        throw new Error('returnClientRequestId must be of type boolean.');
      }
    }
    if (taskAddOptions !== null && taskAddOptions !== undefined)
    {
      ocpDate = taskAddOptions.ocpDate;
      if (ocpDate && !(ocpDate instanceof Date || 
          (typeof ocpDate.valueOf() === 'string' && !isNaN(Date.parse(ocpDate))))) {
            throw new Error('ocpDate must be of type date.');
          }
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  var requestUrl = this.client.baseUri +
                   '//jobs/{jobId}/tasks';
  requestUrl = requestUrl.replace('{jobId}', encodeURIComponent(jobId));
  var queryParameters = [];
  queryParameters.push('api-version=' + encodeURIComponent(this.client.apiVersion));
  if (timeout !== null && timeout !== undefined) {
    queryParameters.push('timeout=' + encodeURIComponent(timeout.toString()));
  }
  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 = 'POST';
  httpRequest.headers = {};
  httpRequest.url = requestUrl;
  // Set Headers
  if (this.client.generateClientRequestId) {
      httpRequest.headers['client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if (clientRequestId !== undefined && clientRequestId !== null) {
    httpRequest.headers['client-request-id'] = clientRequestId;
  }
  if (returnClientRequestId !== undefined && returnClientRequestId !== null) {
    httpRequest.headers['return-client-request-id'] = returnClientRequestId.toString();
  }
  if (ocpDate !== undefined && ocpDate !== null) {
    httpRequest.headers['ocp-date'] = ocpDate.toUTCString();
  }
  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; odata=minimalmetadata; charset=utf-8';
  // Serialize Request
  var requestContent = null;
  var requestModel = null;
  try {
    if (task !== null && task !== undefined) {
      var requestModelMapper = new client.models['TaskAddParameter']().mapper();
      requestModel = client.serialize(requestModelMapper, task, 'task');
      requestContent = JSON.stringify(requestModel);
    }
  } catch (error) {
    var serializationError = new Error(util.format('Error "%s" occurred in serializing the ' + 
        'payload - "%s"', error.message, util.inspect(task, {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 !== 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['BatchError']().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);
  });
};

/**
 * Lists all of the tasks that are associated with the specified job.
 *
 * @param {string} jobId The id of the job.
 * 
 * @param {object} [options] Optional Parameters.
 * 
 * @param {object} [options.taskListOptions] Additional parameters for the
 * operation
 * 
 * @param {string} [options.taskListOptions.filter] An OData $filter clause.
 * 
 * @param {string} [options.taskListOptions.select] An OData $select clause.
 * 
 * @param {string} [options.taskListOptions.expand] An OData $expand clause.
 * 
 * @param {number} [options.taskListOptions.maxResults] The maximum number of
 * items to return in the response.
 * 
 * @param {number} [options.taskListOptions.timeout] The maximum time that the
 * server can spend processing the request, in seconds. The default is 30
 * seconds.
 * 
 * @param {string} [options.taskListOptions.clientRequestId] The
 * caller-generated request identity, in the form of a GUID with no
 * decoration such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0.
 * 
 * @param {boolean} [options.taskListOptions.returnClientRequestId] Whether
 * the server should return the client-request-id identifier in the response.
 * 
 * @param {date} [options.taskListOptions.ocpDate] The time the request was
 * issued. If not specified, this header will be automatically populated with
 * the current system clock time.
 * 
 * @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 CloudTaskListResult} 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.
 */
Task.prototype.list = function (jobId, 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 taskListOptions = (options && options.taskListOptions !== undefined) ? options.taskListOptions : undefined;
  // Validate
  try {
    if (jobId === null || jobId === undefined || typeof jobId.valueOf() !== 'string') {
      throw new Error('jobId 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);
  }
  var filter;
  var select;
  var expand;
  var maxResults;
  var timeout;
  var clientRequestId;
  var returnClientRequestId;
  var ocpDate;
  try {
    if (taskListOptions !== null && taskListOptions !== undefined)
    {
      filter = taskListOptions.filter;
      if (filter !== null && filter !== undefined && typeof filter.valueOf() !== 'string') {
        throw new Error('filter must be of type string.');
      }
    }
    if (taskListOptions !== null && taskListOptions !== undefined)
    {
      select = taskListOptions.select;
      if (select !== null && select !== undefined && typeof select.valueOf() !== 'string') {
        throw new Error('select must be of type string.');
      }
    }
    if (taskListOptions !== null && taskListOptions !== undefined)
    {
      expand = taskListOptions.expand;
      if (expand !== null && expand !== undefined && typeof expand.valueOf() !== 'string') {
        throw new Error('expand must be of type string.');
      }
    }
    if (taskListOptions !== null && taskListOptions !== undefined)
    {
      maxResults = taskListOptions.maxResults;
      if (maxResults !== null && maxResults !== undefined && typeof maxResults !== 'number') {
        throw new Error('maxResults must be of type number.');
      }
    }
    if (taskListOptions !== null && taskListOptions !== undefined)
    {
      timeout = taskListOptions.timeout;
      if (timeout !== null && timeout !== undefined && typeof timeout !== 'number') {
        throw new Error('timeout must be of type number.');
      }
    }
    if (taskListOptions !== null && taskListOptions !== undefined)
    {
      clientRequestId = taskListOptions.clientRequestId;
      if (clientRequestId !== null && clientRequestId !== undefined && typeof clientRequestId.valueOf() !== 'string') {
        throw new Error('clientRequestId must be of type string.');
      }
    }
    if (taskListOptions !== null && taskListOptions !== undefined)
    {
      returnClientRequestId = taskListOptions.returnClientRequestId;
      if (returnClientRequestId !== null && returnClientRequestId !== undefined && typeof returnClientRequestId !== 'boolean') {
        throw new Error('returnClientRequestId must be of type boolean.');
      }
    }
    if (taskListOptions !== null && taskListOptions !== undefined)
    {
      ocpDate = taskListOptions.ocpDate;
      if (ocpDate && !(ocpDate instanceof Date || 
          (typeof ocpDate.valueOf() === 'string' && !isNaN(Date.parse(ocpDate))))) {
            throw new Error('ocpDate must be of type date.');
          }
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  var requestUrl = this.client.baseUri +
                   '//jobs/{jobId}/tasks';
  requestUrl = requestUrl.replace('{jobId}', encodeURIComponent(jobId));
  var queryParameters = [];
  queryParameters.push('api-version=' + encodeURIComponent(this.client.apiVersion));
  if (filter !== null && filter !== undefined) {
    queryParameters.push('$filter=' + encodeURIComponent(filter));
  }
  if (select !== null && select !== undefined) {
    queryParameters.push('$select=' + encodeURIComponent(select));
  }
  if (expand !== null && expand !== undefined) {
    queryParameters.push('$expand=' + encodeURIComponent(expand));
  }
  if (maxResults !== null && maxResults !== undefined) {
    queryParameters.push('maxresults=' + encodeURIComponent(maxResults.toString()));
  }
  if (timeout !== null && timeout !== undefined) {
    queryParameters.push('timeout=' + encodeURIComponent(timeout.toString()));
  }
  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['client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if (clientRequestId !== undefined && clientRequestId !== null) {
    httpRequest.headers['client-request-id'] = clientRequestId;
  }
  if (returnClientRequestId !== undefined && returnClientRequestId !== null) {
    httpRequest.headers['return-client-request-id'] = returnClientRequestId.toString();
  }
  if (ocpDate !== undefined && ocpDate !== null) {
    httpRequest.headers['ocp-date'] = ocpDate.toUTCString();
  }
  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; odata=minimalmetadata; 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['BatchError']().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['CloudTaskListResult']().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);
  });
};

/**
 * @summary Adds a collection of tasks to the specified job.
 *
 * @param {string} jobId The id of the job to which the task collection is to
 * be added.
 * 
 * @param {array} value The collection of tasks to add.
 * 
 * @param {object} [options] Optional Parameters.
 * 
 * @param {object} [options.taskAddCollectionOptions] Additional parameters
 * for the operation
 * 
 * @param {number} [options.taskAddCollectionOptions.timeout] The maximum time
 * that the server can spend processing the request, in seconds. The default
 * is 30 seconds.
 * 
 * @param {string} [options.taskAddCollectionOptions.clientRequestId] The
 * caller-generated request identity, in the form of a GUID with no
 * decoration such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0.
 * 
 * @param {boolean} [options.taskAddCollectionOptions.returnClientRequestId]
 * Whether the server should return the client-request-id identifier in the
 * response.
 * 
 * @param {date} [options.taskAddCollectionOptions.ocpDate] The time the
 * request was issued. If not specified, this header will be automatically
 * populated with the current system clock time.
 * 
 * @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 TaskAddCollectionResult} 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.
 */
Task.prototype.addCollection = function (jobId, value, 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 taskAddCollectionOptions = (options && options.taskAddCollectionOptions !== undefined) ? options.taskAddCollectionOptions : undefined;
  // Validate
  try {
    if (jobId === null || jobId === undefined || typeof jobId.valueOf() !== 'string') {
      throw new Error('jobId 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 (value !== null && value !== undefined) {
      if (value.length > 100)
      {
        throw new Error('"value" should satisfy the constraint - "MaxItems": 100');
      }
    }
    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);
  }
  var timeout;
  var clientRequestId;
  var returnClientRequestId;
  var ocpDate;
  var taskCollection = new client.models['TaskAddCollectionParameter']();
  try {
    if (taskAddCollectionOptions !== null && taskAddCollectionOptions !== undefined)
    {
      timeout = taskAddCollectionOptions.timeout;
      if (timeout !== null && timeout !== undefined && typeof timeout !== 'number') {
        throw new Error('timeout must be of type number.');
      }
    }
    if (taskAddCollectionOptions !== null && taskAddCollectionOptions !== undefined)
    {
      clientRequestId = taskAddCollectionOptions.clientRequestId;
      if (clientRequestId !== null && clientRequestId !== undefined && typeof clientRequestId.valueOf() !== 'string') {
        throw new Error('clientRequestId must be of type string.');
      }
    }
    if (taskAddCollectionOptions !== null && taskAddCollectionOptions !== undefined)
    {
      returnClientRequestId = taskAddCollectionOptions.returnClientRequestId;
      if (returnClientRequestId !== null && returnClientRequestId !== undefined && typeof returnClientRequestId !== 'boolean') {
        throw new Error('returnClientRequestId must be of type boolean.');
      }
    }
    if (taskAddCollectionOptions !== null && taskAddCollectionOptions !== undefined)
    {
      ocpDate = taskAddCollectionOptions.ocpDate;
      if (ocpDate && !(ocpDate instanceof Date || 
          (typeof ocpDate.valueOf() === 'string' && !isNaN(Date.parse(ocpDate))))) {
            throw new Error('ocpDate must be of type date.');
          }
    }
    if (value !== null && value !== undefined)
    {
      taskCollection.value = value;
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  var requestUrl = this.client.baseUri +
                   '//jobs/{jobId}/addtaskcollection';
  requestUrl = requestUrl.replace('{jobId}', encodeURIComponent(jobId));
  var queryParameters = [];
  queryParameters.push('api-version=' + encodeURIComponent(this.client.apiVersion));
  if (timeout !== null && timeout !== undefined) {
    queryParameters.push('timeout=' + encodeURIComponent(timeout.toString()));
  }
  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 = 'POST';
  httpRequest.headers = {};
  httpRequest.url = requestUrl;
  // Set Headers
  if (this.client.generateClientRequestId) {
      httpRequest.headers['client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if (clientRequestId !== undefined && clientRequestId !== null) {
    httpRequest.headers['client-request-id'] = clientRequestId;
  }
  if (returnClientRequestId !== undefined && returnClientRequestId !== null) {
    httpRequest.headers['return-client-request-id'] = returnClientRequestId.toString();
  }
  if (ocpDate !== undefined && ocpDate !== null) {
    httpRequest.headers['ocp-date'] = ocpDate.toUTCString();
  }
  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; odata=minimalmetadata; charset=utf-8';
  // Serialize Request
  var requestContent = null;
  var requestModel = null;
  try {
    if (taskCollection !== null && taskCollection !== undefined) {
      var requestModelMapper = new client.models['TaskAddCollectionParameter']().mapper();
      requestModel = client.serialize(requestModelMapper, taskCollection, 'taskCollection');
      requestContent = JSON.stringify(requestModel);
    }
  } catch (error) {
    var serializationError = new Error(util.format('Error "%s" occurred in serializing the ' + 
        'payload - "%s"', error.message, util.inspect(taskCollection, {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) {
      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['BatchError']().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['TaskAddCollectionResult']().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);
  });
};

/**
 * @summary Deletes a task from the specified job.
 *
 * @param {string} jobId The id of the job from which to delete the task.
 * 
 * @param {string} taskId The id of the task to delete.
 * 
 * @param {object} [options] Optional Parameters.
 * 
 * @param {object} [options.taskDeleteMethodOptions] Additional parameters for
 * the operation
 * 
 * @param {number} [options.taskDeleteMethodOptions.timeout] The maximum time
 * that the server can spend processing the request, in seconds. The default
 * is 30 seconds.
 * 
 * @param {string} [options.taskDeleteMethodOptions.clientRequestId] The
 * caller-generated request identity, in the form of a GUID with no
 * decoration such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0.
 * 
 * @param {boolean} [options.taskDeleteMethodOptions.returnClientRequestId]
 * Whether the server should return the client-request-id identifier in the
 * response.
 * 
 * @param {date} [options.taskDeleteMethodOptions.ocpDate] The time the
 * request was issued. If not specified, this header will be automatically
 * populated with the current system clock time.
 * 
 * @param {string} [options.taskDeleteMethodOptions.ifMatch] An ETag is
 * specified. Specify this header to perform the operation only if the
 * resource's ETag is an exact match as specified.
 * 
 * @param {string} [options.taskDeleteMethodOptions.ifNoneMatch] An ETag is
 * specified. Specify this header to perform the operation only if the
 * resource's ETag does not match the specified ETag.
 * 
 * @param {date} [options.taskDeleteMethodOptions.ifModifiedSince] Specify
 * this header to perform the operation only if the resource has been
 * modified since the specified date/time.
 * 
 * @param {date} [options.taskDeleteMethodOptions.ifUnmodifiedSince] Specify
 * this header to perform the operation only if the resource has not been
 * modified since the specified date/time.
 * 
 * @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.
 */
Task.prototype.deleteMethod = function (jobId, taskId, 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 taskDeleteMethodOptions = (options && options.taskDeleteMethodOptions !== undefined) ? options.taskDeleteMethodOptions : undefined;
  // Validate
  try {
    if (jobId === null || jobId === undefined || typeof jobId.valueOf() !== 'string') {
      throw new Error('jobId cannot be null or undefined and it must be of type string.');
    }
    if (taskId === null || taskId === undefined || typeof taskId.valueOf() !== 'string') {
      throw new Error('taskId 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);
  }
  var timeout;
  var clientRequestId;
  var returnClientRequestId;
  var ocpDate;
  var ifMatch;
  var ifNoneMatch;
  var ifModifiedSince;
  var ifUnmodifiedSince;
  try {
    if (taskDeleteMethodOptions !== null && taskDeleteMethodOptions !== undefined)
    {
      timeout = taskDeleteMethodOptions.timeout;
      if (timeout !== null && timeout !== undefined && typeof timeout !== 'number') {
        throw new Error('timeout must be of type number.');
      }
    }
    if (taskDeleteMethodOptions !== null && taskDeleteMethodOptions !== undefined)
    {
      clientRequestId = taskDeleteMethodOptions.clientRequestId;
      if (clientRequestId !== null && clientRequestId !== undefined && typeof clientRequestId.valueOf() !== 'string') {
        throw new Error('clientRequestId must be of type string.');
      }
    }
    if (taskDeleteMethodOptions !== null && taskDeleteMethodOptions !== undefined)
    {
      returnClientRequestId = taskDeleteMethodOptions.returnClientRequestId;
      if (returnClientRequestId !== null && returnClientRequestId !== undefined && typeof returnClientRequestId !== 'boolean') {
        throw new Error('returnClientRequestId must be of type boolean.');
      }
    }
    if (taskDeleteMethodOptions !== null && taskDeleteMethodOptions !== undefined)
    {
      ocpDate = taskDeleteMethodOptions.ocpDate;
      if (ocpDate && !(ocpDate instanceof Date || 
          (typeof ocpDate.valueOf() === 'string' && !isNaN(Date.parse(ocpDate))))) {
            throw new Error('ocpDate must be of type date.');
          }
    }
    if (taskDeleteMethodOptions !== null && taskDeleteMethodOptions !== undefined)
    {
      ifMatch = taskDeleteMethodOptions.ifMatch;
      if (ifMatch !== null && ifMatch !== undefined && typeof ifMatch.valueOf() !== 'string') {
        throw new Error('ifMatch must be of type string.');
      }
    }
    if (taskDeleteMethodOptions !== null && taskDeleteMethodOptions !== undefined)
    {
      ifNoneMatch = taskDeleteMethodOptions.ifNoneMatch;
      if (ifNoneMatch !== null && ifNoneMatch !== undefined && typeof ifNoneMatch.valueOf() !== 'string') {
        throw new Error('ifNoneMatch must be of type string.');
      }
    }
    if (taskDeleteMethodOptions !== null && taskDeleteMethodOptions !== undefined)
    {
      ifModifiedSince = taskDeleteMethodOptions.ifModifiedSince;
      if (ifModifiedSince && !(ifModifiedSince instanceof Date || 
          (typeof ifModifiedSince.valueOf() === 'string' && !isNaN(Date.parse(ifModifiedSince))))) {
            throw new Error('ifModifiedSince must be of type date.');
          }
    }
    if (taskDeleteMethodOptions !== null && taskDeleteMethodOptions !== undefined)
    {
      ifUnmodifiedSince = taskDeleteMethodOptions.ifUnmodifiedSince;
      if (ifUnmodifiedSince && !(ifUnmodifiedSince instanceof Date || 
          (typeof ifUnmodifiedSince.valueOf() === 'string' && !isNaN(Date.parse(ifUnmodifiedSince))))) {
            throw new Error('ifUnmodifiedSince must be of type date.');
          }
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  var requestUrl = this.client.baseUri +
                   '//jobs/{jobId}/tasks/{taskId}';
  requestUrl = requestUrl.replace('{jobId}', encodeURIComponent(jobId));
  requestUrl = requestUrl.replace('{taskId}', encodeURIComponent(taskId));
  var queryParameters = [];
  queryParameters.push('api-version=' + encodeURIComponent(this.client.apiVersion));
  if (timeout !== null && timeout !== undefined) {
    queryParameters.push('timeout=' + encodeURIComponent(timeout.toString()));
  }
  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['client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if (clientRequestId !== undefined && clientRequestId !== null) {
    httpRequest.headers['client-request-id'] = clientRequestId;
  }
  if (returnClientRequestId !== undefined && returnClientRequestId !== null) {
    httpRequest.headers['return-client-request-id'] = returnClientRequestId.toString();
  }
  if (ocpDate !== undefined && ocpDate !== null) {
    httpRequest.headers['ocp-date'] = ocpDate.toUTCString();
  }
  if (ifMatch !== undefined && ifMatch !== null) {
    httpRequest.headers['If-Match'] = ifMatch;
  }
  if (ifNoneMatch !== undefined && ifNoneMatch !== null) {
    httpRequest.headers['If-None-Match'] = ifNoneMatch;
  }
  if (ifModifiedSince !== undefined && ifModifiedSince !== null) {
    httpRequest.headers['If-Modified-Since'] = ifModifiedSince.toUTCString();
  }
  if (ifUnmodifiedSince !== undefined && ifUnmodifiedSince !== null) {
    httpRequest.headers['If-Unmodified-Since'] = ifUnmodifiedSince.toUTCString();
  }
  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; odata=minimalmetadata; 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['BatchError']().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);
  });
};

/**
 * Gets information about the specified task.
 *
 * @param {string} jobId The id of the job that contains the task.
 * 
 * @param {string} taskId The id of the task to get information about.
 * 
 * @param {object} [options] Optional Parameters.
 * 
 * @param {object} [options.taskGetOptions] Additional parameters for the
 * operation
 * 
 * @param {string} [options.taskGetOptions.select] An OData $select clause.
 * 
 * @param {string} [options.taskGetOptions.expand] An OData $expand clause.
 * 
 * @param {number} [options.taskGetOptions.timeout] The maximum time that the
 * server can spend processing the request, in seconds. The default is 30
 * seconds.
 * 
 * @param {string} [options.taskGetOptions.clientRequestId] The
 * caller-generated request identity, in the form of a GUID with no
 * decoration such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0.
 * 
 * @param {boolean} [options.taskGetOptions.returnClientRequestId] Whether the
 * server should return the client-request-id identifier in the response.
 * 
 * @param {date} [options.taskGetOptions.ocpDate] The time the request was
 * issued. If not specified, this header will be automatically populated with
 * the current system clock time.
 * 
 * @param {string} [options.taskGetOptions.ifMatch] An ETag is specified.
 * Specify this header to perform the operation only if the resource's ETag
 * is an exact match as specified.
 * 
 * @param {string} [options.taskGetOptions.ifNoneMatch] An ETag is specified.
 * Specify this header to perform the operation only if the resource's ETag
 * does not match the specified ETag.
 * 
 * @param {date} [options.taskGetOptions.ifModifiedSince] Specify this header
 * to perform the operation only if the resource has been modified since the
 * specified date/time.
 * 
 * @param {date} [options.taskGetOptions.ifUnmodifiedSince] Specify this
 * header to perform the operation only if the resource has not been modified
 * since the specified date/time.
 * 
 * @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 CloudTask} 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.
 */
Task.prototype.get = function (jobId, taskId, 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 taskGetOptions = (options && options.taskGetOptions !== undefined) ? options.taskGetOptions : undefined;
  // Validate
  try {
    if (jobId === null || jobId === undefined || typeof jobId.valueOf() !== 'string') {
      throw new Error('jobId cannot be null or undefined and it must be of type string.');
    }
    if (taskId === null || taskId === undefined || typeof taskId.valueOf() !== 'string') {
      throw new Error('taskId 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);
  }
  var select;
  var expand;
  var timeout;
  var clientRequestId;
  var returnClientRequestId;
  var ocpDate;
  var ifMatch;
  var ifNoneMatch;
  var ifModifiedSince;
  var ifUnmodifiedSince;
  try {
    if (taskGetOptions !== null && taskGetOptions !== undefined)
    {
      select = taskGetOptions.select;
      if (select !== null && select !== undefined && typeof select.valueOf() !== 'string') {
        throw new Error('select must be of type string.');
      }
    }
    if (taskGetOptions !== null && taskGetOptions !== undefined)
    {
      expand = taskGetOptions.expand;
      if (expand !== null && expand !== undefined && typeof expand.valueOf() !== 'string') {
        throw new Error('expand must be of type string.');
      }
    }
    if (taskGetOptions !== null && taskGetOptions !== undefined)
    {
      timeout = taskGetOptions.timeout;
      if (timeout !== null && timeout !== undefined && typeof timeout !== 'number') {
        throw new Error('timeout must be of type number.');
      }
    }
    if (taskGetOptions !== null && taskGetOptions !== undefined)
    {
      clientRequestId = taskGetOptions.clientRequestId;
      if (clientRequestId !== null && clientRequestId !== undefined && typeof clientRequestId.valueOf() !== 'string') {
        throw new Error('clientRequestId must be of type string.');
      }
    }
    if (taskGetOptions !== null && taskGetOptions !== undefined)
    {
      returnClientRequestId = taskGetOptions.returnClientRequestId;
      if (returnClientRequestId !== null && returnClientRequestId !== undefined && typeof returnClientRequestId !== 'boolean') {
        throw new Error('returnClientRequestId must be of type boolean.');
      }
    }
    if (taskGetOptions !== null && taskGetOptions !== undefined)
    {
      ocpDate = taskGetOptions.ocpDate;
      if (ocpDate && !(ocpDate instanceof Date || 
          (typeof ocpDate.valueOf() === 'string' && !isNaN(Date.parse(ocpDate))))) {
            throw new Error('ocpDate must be of type date.');
          }
    }
    if (taskGetOptions !== null && taskGetOptions !== undefined)
    {
      ifMatch = taskGetOptions.ifMatch;
      if (ifMatch !== null && ifMatch !== undefined && typeof ifMatch.valueOf() !== 'string') {
        throw new Error('ifMatch must be of type string.');
      }
    }
    if (taskGetOptions !== null && taskGetOptions !== undefined)
    {
      ifNoneMatch = taskGetOptions.ifNoneMatch;
      if (ifNoneMatch !== null && ifNoneMatch !== undefined && typeof ifNoneMatch.valueOf() !== 'string') {
        throw new Error('ifNoneMatch must be of type string.');
      }
    }
    if (taskGetOptions !== null && taskGetOptions !== undefined)
    {
      ifModifiedSince = taskGetOptions.ifModifiedSince;
      if (ifModifiedSince && !(ifModifiedSince instanceof Date || 
          (typeof ifModifiedSince.valueOf() === 'string' && !isNaN(Date.parse(ifModifiedSince))))) {
            throw new Error('ifModifiedSince must be of type date.');
          }
    }
    if (taskGetOptions !== null && taskGetOptions !== undefined)
    {
      ifUnmodifiedSince = taskGetOptions.ifUnmodifiedSince;
      if (ifUnmodifiedSince && !(ifUnmodifiedSince instanceof Date || 
          (typeof ifUnmodifiedSince.valueOf() === 'string' && !isNaN(Date.parse(ifUnmodifiedSince))))) {
            throw new Error('ifUnmodifiedSince must be of type date.');
          }
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  var requestUrl = this.client.baseUri +
                   '//jobs/{jobId}/tasks/{taskId}';
  requestUrl = requestUrl.replace('{jobId}', encodeURIComponent(jobId));
  requestUrl = requestUrl.replace('{taskId}', encodeURIComponent(taskId));
  var queryParameters = [];
  queryParameters.push('api-version=' + encodeURIComponent(this.client.apiVersion));
  if (select !== null && select !== undefined) {
    queryParameters.push('$select=' + encodeURIComponent(select));
  }
  if (expand !== null && expand !== undefined) {
    queryParameters.push('$expand=' + encodeURIComponent(expand));
  }
  if (timeout !== null && timeout !== undefined) {
    queryParameters.push('timeout=' + encodeURIComponent(timeout.toString()));
  }
  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['client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if (clientRequestId !== undefined && clientRequestId !== null) {
    httpRequest.headers['client-request-id'] = clientRequestId;
  }
  if (returnClientRequestId !== undefined && returnClientRequestId !== null) {
    httpRequest.headers['return-client-request-id'] = returnClientRequestId.toString();
  }
  if (ocpDate !== undefined && ocpDate !== null) {
    httpRequest.headers['ocp-date'] = ocpDate.toUTCString();
  }
  if (ifMatch !== undefined && ifMatch !== null) {
    httpRequest.headers['If-Match'] = ifMatch;
  }
  if (ifNoneMatch !== undefined && ifNoneMatch !== null) {
    httpRequest.headers['If-None-Match'] = ifNoneMatch;
  }
  if (ifModifiedSince !== undefined && ifModifiedSince !== null) {
    httpRequest.headers['If-Modified-Since'] = ifModifiedSince.toUTCString();
  }
  if (ifUnmodifiedSince !== undefined && ifUnmodifiedSince !== null) {
    httpRequest.headers['If-Unmodified-Since'] = ifUnmodifiedSince.toUTCString();
  }
  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; odata=minimalmetadata; 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['BatchError']().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['CloudTask']().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);
  });
};

/**
 * Updates the properties of the specified task.
 *
 * @param {string} jobId The id of the job containing the task.
 * 
 * @param {string} taskId The id of the task to update.
 * 
 * @param {object} [options] Optional Parameters.
 * 
 * @param {object} [options.constraints] Constraints that apply to this task.
 * If omitted, the task is given the default constraints.
 * 
 * @param {moment.duration} [options.constraints.maxWallClockTime] The maximum
 * elapsed time that the task may run, measured from the time the task
 * starts. If the task does not complete within the time limit, the Batch
 * service terminates it.
 * 
 * @param {moment.duration} [options.constraints.retentionTime] The minimum
 * time to retain the working directory for the task on the compute node
 * where it ran, from the time it completes execution. After this time, the
 * Batch service may delete the working directory and all its contents. The
 * default is infinite.
 * 
 * @param {number} [options.constraints.maxTaskRetryCount] The maximum number
 * of times the task may be retried. The Batch service retries a task if its
 * exit code is nonzero.
 * 
 * @param {object} [options.taskUpdateOptions] Additional parameters for the
 * operation
 * 
 * @param {number} [options.taskUpdateOptions.timeout] The maximum time that
 * the server can spend processing the request, in seconds. The default is 30
 * seconds.
 * 
 * @param {string} [options.taskUpdateOptions.clientRequestId] The
 * caller-generated request identity, in the form of a GUID with no
 * decoration such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0.
 * 
 * @param {boolean} [options.taskUpdateOptions.returnClientRequestId] Whether
 * the server should return the client-request-id identifier in the response.
 * 
 * @param {date} [options.taskUpdateOptions.ocpDate] The time the request was
 * issued. If not specified, this header will be automatically populated with
 * the current system clock time.
 * 
 * @param {string} [options.taskUpdateOptions.ifMatch] An ETag is specified.
 * Specify this header to perform the operation only if the resource's ETag
 * is an exact match as specified.
 * 
 * @param {string} [options.taskUpdateOptions.ifNoneMatch] An ETag is
 * specified. Specify this header to perform the operation only if the
 * resource's ETag does not match the specified ETag.
 * 
 * @param {date} [options.taskUpdateOptions.ifModifiedSince] Specify this
 * header to perform the operation only if the resource has been modified
 * since the specified date/time.
 * 
 * @param {date} [options.taskUpdateOptions.ifUnmodifiedSince] Specify this
 * header to perform the operation only if the resource has not been modified
 * since the specified date/time.
 * 
 * @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.
 */
Task.prototype.update = function (jobId, taskId, 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 constraints = (options && options.constraints !== undefined) ? options.constraints : undefined;
  var taskUpdateOptions = (options && options.taskUpdateOptions !== undefined) ? options.taskUpdateOptions : undefined;
  // Validate
  try {
    if (jobId === null || jobId === undefined || typeof jobId.valueOf() !== 'string') {
      throw new Error('jobId cannot be null or undefined and it must be of type string.');
    }
    if (taskId === null || taskId === undefined || typeof taskId.valueOf() !== 'string') {
      throw new Error('taskId 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);
  }
  var timeout;
  var clientRequestId;
  var returnClientRequestId;
  var ocpDate;
  var ifMatch;
  var ifNoneMatch;
  var ifModifiedSince;
  var ifUnmodifiedSince;
  var taskUpdateParameter = new client.models['TaskUpdateParameter']();
  try {
    if (taskUpdateOptions !== null && taskUpdateOptions !== undefined)
    {
      timeout = taskUpdateOptions.timeout;
      if (timeout !== null && timeout !== undefined && typeof timeout !== 'number') {
        throw new Error('timeout must be of type number.');
      }
    }
    if (taskUpdateOptions !== null && taskUpdateOptions !== undefined)
    {
      clientRequestId = taskUpdateOptions.clientRequestId;
      if (clientRequestId !== null && clientRequestId !== undefined && typeof clientRequestId.valueOf() !== 'string') {
        throw new Error('clientRequestId must be of type string.');
      }
    }
    if (taskUpdateOptions !== null && taskUpdateOptions !== undefined)
    {
      returnClientRequestId = taskUpdateOptions.returnClientRequestId;
      if (returnClientRequestId !== null && returnClientRequestId !== undefined && typeof returnClientRequestId !== 'boolean') {
        throw new Error('returnClientRequestId must be of type boolean.');
      }
    }
    if (taskUpdateOptions !== null && taskUpdateOptions !== undefined)
    {
      ocpDate = taskUpdateOptions.ocpDate;
      if (ocpDate && !(ocpDate instanceof Date || 
          (typeof ocpDate.valueOf() === 'string' && !isNaN(Date.parse(ocpDate))))) {
            throw new Error('ocpDate must be of type date.');
          }
    }
    if (taskUpdateOptions !== null && taskUpdateOptions !== undefined)
    {
      ifMatch = taskUpdateOptions.ifMatch;
      if (ifMatch !== null && ifMatch !== undefined && typeof ifMatch.valueOf() !== 'string') {
        throw new Error('ifMatch must be of type string.');
      }
    }
    if (taskUpdateOptions !== null && taskUpdateOptions !== undefined)
    {
      ifNoneMatch = taskUpdateOptions.ifNoneMatch;
      if (ifNoneMatch !== null && ifNoneMatch !== undefined && typeof ifNoneMatch.valueOf() !== 'string') {
        throw new Error('ifNoneMatch must be of type string.');
      }
    }
    if (taskUpdateOptions !== null && taskUpdateOptions !== undefined)
    {
      ifModifiedSince = taskUpdateOptions.ifModifiedSince;
      if (ifModifiedSince && !(ifModifiedSince instanceof Date || 
          (typeof ifModifiedSince.valueOf() === 'string' && !isNaN(Date.parse(ifModifiedSince))))) {
            throw new Error('ifModifiedSince must be of type date.');
          }
    }
    if (taskUpdateOptions !== null && taskUpdateOptions !== undefined)
    {
      ifUnmodifiedSince = taskUpdateOptions.ifUnmodifiedSince;
      if (ifUnmodifiedSince && !(ifUnmodifiedSince instanceof Date || 
          (typeof ifUnmodifiedSince.valueOf() === 'string' && !isNaN(Date.parse(ifUnmodifiedSince))))) {
            throw new Error('ifUnmodifiedSince must be of type date.');
          }
    }
    if (constraints !== null && constraints !== undefined)
    {
      taskUpdateParameter.constraints = constraints;
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  var requestUrl = this.client.baseUri +
                   '//jobs/{jobId}/tasks/{taskId}';
  requestUrl = requestUrl.replace('{jobId}', encodeURIComponent(jobId));
  requestUrl = requestUrl.replace('{taskId}', encodeURIComponent(taskId));
  var queryParameters = [];
  queryParameters.push('api-version=' + encodeURIComponent(this.client.apiVersion));
  if (timeout !== null && timeout !== undefined) {
    queryParameters.push('timeout=' + encodeURIComponent(timeout.toString()));
  }
  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['client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if (clientRequestId !== undefined && clientRequestId !== null) {
    httpRequest.headers['client-request-id'] = clientRequestId;
  }
  if (returnClientRequestId !== undefined && returnClientRequestId !== null) {
    httpRequest.headers['return-client-request-id'] = returnClientRequestId.toString();
  }
  if (ocpDate !== undefined && ocpDate !== null) {
    httpRequest.headers['ocp-date'] = ocpDate.toUTCString();
  }
  if (ifMatch !== undefined && ifMatch !== null) {
    httpRequest.headers['If-Match'] = ifMatch;
  }
  if (ifNoneMatch !== undefined && ifNoneMatch !== null) {
    httpRequest.headers['If-None-Match'] = ifNoneMatch;
  }
  if (ifModifiedSince !== undefined && ifModifiedSince !== null) {
    httpRequest.headers['If-Modified-Since'] = ifModifiedSince.toUTCString();
  }
  if (ifUnmodifiedSince !== undefined && ifUnmodifiedSince !== null) {
    httpRequest.headers['If-Unmodified-Since'] = ifUnmodifiedSince.toUTCString();
  }
  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; odata=minimalmetadata; charset=utf-8';
  // Serialize Request
  var requestContent = null;
  var requestModel = null;
  try {
    if (taskUpdateParameter !== null && taskUpdateParameter !== undefined) {
      var requestModelMapper = new client.models['TaskUpdateParameter']().mapper();
      requestModel = client.serialize(requestModelMapper, taskUpdateParameter, 'taskUpdateParameter');
      requestContent = JSON.stringify(requestModel);
    }
  } catch (error) {
    var serializationError = new Error(util.format('Error "%s" occurred in serializing the ' + 
        'payload - "%s"', error.message, util.inspect(taskUpdateParameter, {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) {
      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['BatchError']().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);
  });
};

/**
 * @summary Lists all of the subtasks that are associated with the specified
 * multi-instance task.
 *
 * @param {string} jobId The id of the job.
 * 
 * @param {string} taskId The id of the task.
 * 
 * @param {object} [options] Optional Parameters.
 * 
 * @param {object} [options.taskListSubtasksOptions] Additional parameters for
 * the operation
 * 
 * @param {string} [options.taskListSubtasksOptions.select] An OData $select
 * clause.
 * 
 * @param {number} [options.taskListSubtasksOptions.timeout] The maximum time
 * that the server can spend processing the request, in seconds. The default
 * is 30 seconds.
 * 
 * @param {string} [options.taskListSubtasksOptions.clientRequestId] The
 * caller-generated request identity, in the form of a GUID with no
 * decoration such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0.
 * 
 * @param {boolean} [options.taskListSubtasksOptions.returnClientRequestId]
 * Whether the server should return the client-request-id identifier in the
 * response.
 * 
 * @param {date} [options.taskListSubtasksOptions.ocpDate] The time the
 * request was issued. If not specified, this header will be automatically
 * populated with the current system clock time.
 * 
 * @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 CloudTaskListSubtasksResult} 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.
 */
Task.prototype.listSubtasks = function (jobId, taskId, 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 taskListSubtasksOptions = (options && options.taskListSubtasksOptions !== undefined) ? options.taskListSubtasksOptions : undefined;
  // Validate
  try {
    if (jobId === null || jobId === undefined || typeof jobId.valueOf() !== 'string') {
      throw new Error('jobId cannot be null or undefined and it must be of type string.');
    }
    if (taskId === null || taskId === undefined || typeof taskId.valueOf() !== 'string') {
      throw new Error('taskId 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);
  }
  var select;
  var timeout;
  var clientRequestId;
  var returnClientRequestId;
  var ocpDate;
  try {
    if (taskListSubtasksOptions !== null && taskListSubtasksOptions !== undefined)
    {
      select = taskListSubtasksOptions.select;
      if (select !== null && select !== undefined && typeof select.valueOf() !== 'string') {
        throw new Error('select must be of type string.');
      }
    }
    if (taskListSubtasksOptions !== null && taskListSubtasksOptions !== undefined)
    {
      timeout = taskListSubtasksOptions.timeout;
      if (timeout !== null && timeout !== undefined && typeof timeout !== 'number') {
        throw new Error('timeout must be of type number.');
      }
    }
    if (taskListSubtasksOptions !== null && taskListSubtasksOptions !== undefined)
    {
      clientRequestId = taskListSubtasksOptions.clientRequestId;
      if (clientRequestId !== null && clientRequestId !== undefined && typeof clientRequestId.valueOf() !== 'string') {
        throw new Error('clientRequestId must be of type string.');
      }
    }
    if (taskListSubtasksOptions !== null && taskListSubtasksOptions !== undefined)
    {
      returnClientRequestId = taskListSubtasksOptions.returnClientRequestId;
      if (returnClientRequestId !== null && returnClientRequestId !== undefined && typeof returnClientRequestId !== 'boolean') {
        throw new Error('returnClientRequestId must be of type boolean.');
      }
    }
    if (taskListSubtasksOptions !== null && taskListSubtasksOptions !== undefined)
    {
      ocpDate = taskListSubtasksOptions.ocpDate;
      if (ocpDate && !(ocpDate instanceof Date || 
          (typeof ocpDate.valueOf() === 'string' && !isNaN(Date.parse(ocpDate))))) {
            throw new Error('ocpDate must be of type date.');
          }
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  var requestUrl = this.client.baseUri +
                   '//jobs/{jobId}/tasks/{taskId}/subtasksinfo';
  requestUrl = requestUrl.replace('{jobId}', encodeURIComponent(jobId));
  requestUrl = requestUrl.replace('{taskId}', encodeURIComponent(taskId));
  var queryParameters = [];
  queryParameters.push('api-version=' + encodeURIComponent(this.client.apiVersion));
  if (select !== null && select !== undefined) {
    queryParameters.push('$select=' + encodeURIComponent(select));
  }
  if (timeout !== null && timeout !== undefined) {
    queryParameters.push('timeout=' + encodeURIComponent(timeout.toString()));
  }
  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['client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if (clientRequestId !== undefined && clientRequestId !== null) {
    httpRequest.headers['client-request-id'] = clientRequestId;
  }
  if (returnClientRequestId !== undefined && returnClientRequestId !== null) {
    httpRequest.headers['return-client-request-id'] = returnClientRequestId.toString();
  }
  if (ocpDate !== undefined && ocpDate !== null) {
    httpRequest.headers['ocp-date'] = ocpDate.toUTCString();
  }
  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; odata=minimalmetadata; 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['BatchError']().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['CloudTaskListSubtasksResult']().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);
  });
};

/**
 * @summary Terminates the specified task.
 *
 * @param {string} jobId The id of the job containing the task.
 * 
 * @param {string} taskId The id of the task to terminate.
 * 
 * @param {object} [options] Optional Parameters.
 * 
 * @param {object} [options.taskTerminateOptions] Additional parameters for
 * the operation
 * 
 * @param {number} [options.taskTerminateOptions.timeout] The maximum time
 * that the server can spend processing the request, in seconds. The default
 * is 30 seconds.
 * 
 * @param {string} [options.taskTerminateOptions.clientRequestId] The
 * caller-generated request identity, in the form of a GUID with no
 * decoration such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0.
 * 
 * @param {boolean} [options.taskTerminateOptions.returnClientRequestId]
 * Whether the server should return the client-request-id identifier in the
 * response.
 * 
 * @param {date} [options.taskTerminateOptions.ocpDate] The time the request
 * was issued. If not specified, this header will be automatically populated
 * with the current system clock time.
 * 
 * @param {string} [options.taskTerminateOptions.ifMatch] An ETag is
 * specified. Specify this header to perform the operation only if the
 * resource's ETag is an exact match as specified.
 * 
 * @param {string} [options.taskTerminateOptions.ifNoneMatch] An ETag is
 * specified. Specify this header to perform the operation only if the
 * resource's ETag does not match the specified ETag.
 * 
 * @param {date} [options.taskTerminateOptions.ifModifiedSince] Specify this
 * header to perform the operation only if the resource has been modified
 * since the specified date/time.
 * 
 * @param {date} [options.taskTerminateOptions.ifUnmodifiedSince] Specify this
 * header to perform the operation only if the resource has not been modified
 * since the specified date/time.
 * 
 * @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.
 */
Task.prototype.terminate = function (jobId, taskId, 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 taskTerminateOptions = (options && options.taskTerminateOptions !== undefined) ? options.taskTerminateOptions : undefined;
  // Validate
  try {
    if (jobId === null || jobId === undefined || typeof jobId.valueOf() !== 'string') {
      throw new Error('jobId cannot be null or undefined and it must be of type string.');
    }
    if (taskId === null || taskId === undefined || typeof taskId.valueOf() !== 'string') {
      throw new Error('taskId 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);
  }
  var timeout;
  var clientRequestId;
  var returnClientRequestId;
  var ocpDate;
  var ifMatch;
  var ifNoneMatch;
  var ifModifiedSince;
  var ifUnmodifiedSince;
  try {
    if (taskTerminateOptions !== null && taskTerminateOptions !== undefined)
    {
      timeout = taskTerminateOptions.timeout;
      if (timeout !== null && timeout !== undefined && typeof timeout !== 'number') {
        throw new Error('timeout must be of type number.');
      }
    }
    if (taskTerminateOptions !== null && taskTerminateOptions !== undefined)
    {
      clientRequestId = taskTerminateOptions.clientRequestId;
      if (clientRequestId !== null && clientRequestId !== undefined && typeof clientRequestId.valueOf() !== 'string') {
        throw new Error('clientRequestId must be of type string.');
      }
    }
    if (taskTerminateOptions !== null && taskTerminateOptions !== undefined)
    {
      returnClientRequestId = taskTerminateOptions.returnClientRequestId;
      if (returnClientRequestId !== null && returnClientRequestId !== undefined && typeof returnClientRequestId !== 'boolean') {
        throw new Error('returnClientRequestId must be of type boolean.');
      }
    }
    if (taskTerminateOptions !== null && taskTerminateOptions !== undefined)
    {
      ocpDate = taskTerminateOptions.ocpDate;
      if (ocpDate && !(ocpDate instanceof Date || 
          (typeof ocpDate.valueOf() === 'string' && !isNaN(Date.parse(ocpDate))))) {
            throw new Error('ocpDate must be of type date.');
          }
    }
    if (taskTerminateOptions !== null && taskTerminateOptions !== undefined)
    {
      ifMatch = taskTerminateOptions.ifMatch;
      if (ifMatch !== null && ifMatch !== undefined && typeof ifMatch.valueOf() !== 'string') {
        throw new Error('ifMatch must be of type string.');
      }
    }
    if (taskTerminateOptions !== null && taskTerminateOptions !== undefined)
    {
      ifNoneMatch = taskTerminateOptions.ifNoneMatch;
      if (ifNoneMatch !== null && ifNoneMatch !== undefined && typeof ifNoneMatch.valueOf() !== 'string') {
        throw new Error('ifNoneMatch must be of type string.');
      }
    }
    if (taskTerminateOptions !== null && taskTerminateOptions !== undefined)
    {
      ifModifiedSince = taskTerminateOptions.ifModifiedSince;
      if (ifModifiedSince && !(ifModifiedSince instanceof Date || 
          (typeof ifModifiedSince.valueOf() === 'string' && !isNaN(Date.parse(ifModifiedSince))))) {
            throw new Error('ifModifiedSince must be of type date.');
          }
    }
    if (taskTerminateOptions !== null && taskTerminateOptions !== undefined)
    {
      ifUnmodifiedSince = taskTerminateOptions.ifUnmodifiedSince;
      if (ifUnmodifiedSince && !(ifUnmodifiedSince instanceof Date || 
          (typeof ifUnmodifiedSince.valueOf() === 'string' && !isNaN(Date.parse(ifUnmodifiedSince))))) {
            throw new Error('ifUnmodifiedSince must be of type date.');
          }
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  var requestUrl = this.client.baseUri +
                   '//jobs/{jobId}/tasks/{taskId}/terminate';
  requestUrl = requestUrl.replace('{jobId}', encodeURIComponent(jobId));
  requestUrl = requestUrl.replace('{taskId}', encodeURIComponent(taskId));
  var queryParameters = [];
  queryParameters.push('api-version=' + encodeURIComponent(this.client.apiVersion));
  if (timeout !== null && timeout !== undefined) {
    queryParameters.push('timeout=' + encodeURIComponent(timeout.toString()));
  }
  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 = 'POST';
  httpRequest.headers = {};
  httpRequest.url = requestUrl;
  // Set Headers
  if (this.client.generateClientRequestId) {
      httpRequest.headers['client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if (clientRequestId !== undefined && clientRequestId !== null) {
    httpRequest.headers['client-request-id'] = clientRequestId;
  }
  if (returnClientRequestId !== undefined && returnClientRequestId !== null) {
    httpRequest.headers['return-client-request-id'] = returnClientRequestId.toString();
  }
  if (ocpDate !== undefined && ocpDate !== null) {
    httpRequest.headers['ocp-date'] = ocpDate.toUTCString();
  }
  if (ifMatch !== undefined && ifMatch !== null) {
    httpRequest.headers['If-Match'] = ifMatch;
  }
  if (ifNoneMatch !== undefined && ifNoneMatch !== null) {
    httpRequest.headers['If-None-Match'] = ifNoneMatch;
  }
  if (ifModifiedSince !== undefined && ifModifiedSince !== null) {
    httpRequest.headers['If-Modified-Since'] = ifModifiedSince.toUTCString();
  }
  if (ifUnmodifiedSince !== undefined && ifUnmodifiedSince !== null) {
    httpRequest.headers['If-Unmodified-Since'] = ifUnmodifiedSince.toUTCString();
  }
  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; odata=minimalmetadata; 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 !== 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['BatchError']().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);
  });
};

/**
 * Lists all of the tasks that are associated with the specified job.
 *
 * @param {string} nextPageLink The NextLink from the previous successful call
 * to List operation.
 * 
 * @param {object} [options] Optional Parameters.
 * 
 * @param {object} [options.taskListNextOptions] Additional parameters for the
 * operation
 * 
 * @param {string} [options.taskListNextOptions.clientRequestId] The
 * caller-generated request identity, in the form of a GUID with no
 * decoration such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0.
 * 
 * @param {boolean} [options.taskListNextOptions.returnClientRequestId]
 * Whether the server should return the client-request-id identifier in the
 * response.
 * 
 * @param {date} [options.taskListNextOptions.ocpDate] The time the request
 * was issued. If not specified, this header will be automatically populated
 * with the current system clock time.
 * 
 * @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 CloudTaskListResult} 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.
 */
Task.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.');
  }
  var taskListNextOptions = (options && options.taskListNextOptions !== undefined) ? options.taskListNextOptions : undefined;
  // 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);
  }
  var clientRequestId;
  var returnClientRequestId;
  var ocpDate;
  try {
    if (taskListNextOptions !== null && taskListNextOptions !== undefined)
    {
      clientRequestId = taskListNextOptions.clientRequestId;
      if (clientRequestId !== null && clientRequestId !== undefined && typeof clientRequestId.valueOf() !== 'string') {
        throw new Error('clientRequestId must be of type string.');
      }
    }
    if (taskListNextOptions !== null && taskListNextOptions !== undefined)
    {
      returnClientRequestId = taskListNextOptions.returnClientRequestId;
      if (returnClientRequestId !== null && returnClientRequestId !== undefined && typeof returnClientRequestId !== 'boolean') {
        throw new Error('returnClientRequestId must be of type boolean.');
      }
    }
    if (taskListNextOptions !== null && taskListNextOptions !== undefined)
    {
      ocpDate = taskListNextOptions.ocpDate;
      if (ocpDate && !(ocpDate instanceof Date || 
          (typeof ocpDate.valueOf() === 'string' && !isNaN(Date.parse(ocpDate))))) {
            throw new Error('ocpDate must be of type date.');
          }
    }
  } 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['client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if (clientRequestId !== undefined && clientRequestId !== null) {
    httpRequest.headers['client-request-id'] = clientRequestId;
  }
  if (returnClientRequestId !== undefined && returnClientRequestId !== null) {
    httpRequest.headers['return-client-request-id'] = returnClientRequestId.toString();
  }
  if (ocpDate !== undefined && ocpDate !== null) {
    httpRequest.headers['ocp-date'] = ocpDate.toUTCString();
  }
  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; odata=minimalmetadata; 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['BatchError']().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['CloudTaskListResult']().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 = Task;
