 
 process.on 'SIGUSR2', -> logger.reopenFileStreams()
 
+importFn = (fileName) ->
+  throw new Error 'You must provide a file to be processed' unless fileName
+  d = Q.defer()
+  logger.info "About to process file #{fileName}"
+  mode = stockimport.getMode fileName
+  fs.read fileName
+  .then (content) ->
+    logger.info 'File read, running import'
+    stockimport.run(content, mode)
+    .then (result) ->
+      logger.info stockimport.sumResult(result)
+      d.resolve(fileName)
+    .fail (e) ->
+      logger.error e, "Oops, something went wrong when processing file #{fileName}"
+      d.reject 1
+  .fail (e) ->
+    logger.error e, "Cannot read file #{fileName}"
+    d.reject 2
+  d.promise
+
+processFn = (files, fn) ->
+  throw new Error 'Please provide a function to process the files' unless _.isFunction fn
+  d = Q.defer()
+  _process = (tick) ->
+    logger.info tick, 'Current tick'
+    if tick >= files.length
+      logger.info 'No more files, resolving...'
+      d.resolve()
+    else
+      file = files[tick]
+      fn(file)
+      .then ->
+        logger.info "Finishing processing file #{file}"
+        sftpHelper.finish(file)
+      .then ->
+        _process(tick + 1)
+      .fail (error) -> d.reject error
+      .done()
+  _process(0)
+  d.promise
+
 credentialsConfig = ProjectCredentialsConfig.create()
-.fail (err) ->
-  logger.error e, "Problems on getting client credentials from config files."
 .then (credentials) ->
   options =
     config: credentials.enrichCredentials

      targetFolder: argv.sftpTarget
      logger: logger

    processFn = (files, fn) ->
      throw new Error 'Please provide a function to process the files' unless _.isFunction fn
      d = Q.defer()
      _process = (tick) ->
        logger.info tick, 'Current tick'
        if tick >= files.length
          logger.info 'No more files, resolving...'
          d.resolve()
        else
          file = files[tick]
          fn(file)
          .then ->
            logger.info "Finishing processing file #{file}"
            sftpHelper.finish(file)
          .then ->
            _process(tick + 1)
          .fail (error) -> d.reject error
          .done()
      _process(0)
      d.promise

    sftpHelper.download(TMP_PATH)
    .then (files) ->
      logger.info files, "Processing #{files.length} files..."

Q = require 'q'
_ = require 'underscore'
path = require 'path'
{ProjectCredentialsConfig} = require 'sphere-node-utils'
package_json = require '../package.json'
Logger = require './logger'
StockImport = require './stockimport'
SftpHelper = require './sftp'

argv = require('optimist')
  .usage('Usage: $0 --projectKey [key] --clientId [id] --clientSecret [secret] --file [file] --logDir [dir] --logLevel [level]')
