 TaskModel = require('../model/tasks').Task
+Channel = require('../model/channels').Channel
 Q = require("q")
 logger = require("winston")
 monq = require("monq")

      return callback err, null

    # setup the option object for the HTTP Request
    rerunSetHTTPRequestOptions transaction, taskID, (err, options) ->

      if err
        logger.error(err)
        return callback err, null

      #############################################################################
      ### The job has processed correctly and is preparing to send HTTP Request ###
      ### Move on to another job while this one waits for HTTPResponse to save  ###
      ###     the result - "callback null, trasnactionID" completes the job     ###
      #############################################################################
      callback null, transactionID
      
      # Run the HTTP Request with details supplied in options object
      rerunHttpRequestSend options, transaction, (err, HTTPResponse) ->

        if err
          logger.error(err)
          return callback err, null

        # Update the task object with the response details
        rerunUpdateTaskObject taskID, transactionID, HTTPResponse, (err, updatedTask) ->

          if err
            logger.error(err)
            return callback err, null

exports.startupWorker = ->
  worker.start()

# Function for updating the task object with response details #
###############################################################

rerunTcpRequestSend = (channel, transaction, callback) ->

  response =
    body: ''
    transaction: {}

  client = new net.Socket()

  client.connect channel.tcpPort, channel.tcpHost, ->
    console.log "Connected"
    client.end transaction.request.body
    return

  client.on "data", (data) ->
    console.log "Received: " + data
    response.body += data
    client.destroy() # kill client after server's response

  client.on "end" , (err) ->
    console.log "Connection closed"
    response.status = 200
    response.transaction.status = "Completed"
    response.message = ''
    response.headers = {}
    response.timestamp = new Date

    logger.info('Rerun Transaction #' + transaction._id + ' - TCP Response has been captured')
    callback err, response
    return

#########################################################
# Export these functions when in the "test" environment #
