var _ = fis.util;
var path = require('path');
var settings = require('../conf/settings');

function upload(receiver, to, data, release, content, file, callback) {
  var subpath = file.subpath;
  data['to'] = _(path.join(to, release));
  fis.util.upload(
    //url, request options, post data, file
    receiver, null, data, content, subpath,
    function (err, res) {
      if (err || res.trim() != '0') {
        callback('upload file [' + subpath + '] to [' + to + '] by receiver [' + receiver + '] error [' + (err || res) + ']');
      } else {
        var time = '[' + fis.log.now(true) + ']';
        process.stdout.write(
          ' - '.green.bold +
          time.grey + ' ' +
          subpath.replace(/^\//, '') +
          ' >> '.yellow.bold +
          to + release +
          '\n'
        );
        callback();
      }
    }
  );
}

module.exports = function (modified, root) {
  return function () {
    var to = path.join('/www', settings.wwwDeployDir, root);// 注意这个是指的是测试机器的路径，而非本地机器
    var receiver = settings.wwwUploadScript;
    var steps = [];

    modified.forEach(function (file) {
      var reTryCount = 2;
      steps.push(function (next) {
        var _upload = arguments.callee;

        upload(receiver, to, {}, file.getHashRelease(), file.getContent(), file, function (error) {
          if (error) {
            if (!--reTryCount) {
              throw new Error(error);
            } else {
              _upload();
            }
          } else {
            next();
          }
        });
      });
    });

    _.reduceRight(steps, function (next, current) {
      return function () {
        current(next);
      };
    }, arguments[3])();
  };
};
