//hoo prod <path> 自动发布到svn代码库和测试环境,并打开网页
var path = require('path');
var settings = require('../settings');
var mkdirp = require('mkdirp');
var _ = require('../../lib/util');
module.exports = function (hoo, root, del_flag,relative, deployMsg) {
  require('./production')(hoo, root, 'deploy',relative);
  hoo.match('**', {
    deploy: [
      hoo.plugin('skip-packed', {
        // 配置项
        skipPackedToPkg: true,//是否过滤掉被打包的文件
        skipPackedToAIO: true,//是否过滤掉被 AllInOne 打包的文件
        skipPackedToCssSprite: true,//是否过滤掉被 css sprite 合并的文件。
        ignore: []//即便设置了过滤，但是如果目标文件 ignore 列表中，还是不会被过滤。glob 语法，数组或者字符串。
      }),
      //去掉多余的模板文件
      function (options, modified, total, next) {
        var i = modified.length - 1;
        var file;
        while ((file = modified[i--])) {
          if (file.isHtmlLike&&file.isInline) {
            modified.splice(i+1,1);
          }
        }
        next();
      },
      //去掉产出相对路径时的bug
      function (options, modified, total, next) {
        var i = modified.length - 1;
        var file;
        while ((file = modified[i--])) {
          if (file.isJsLike) {
            file.setContent(file.getContent().replace(/&quot;(\/)*/g, ''));
          }
        }
        next();
      },
      hoo.plugin('local-deliver', {
        to: path.join(settings.deployDir, root)
      })
    ]
  });

  var workCopy = path.join(process.cwd(), settings.deployDir, root);
  //release之前首先清空dist目录，并从svn库更新当前活动专题目录
  hoo.on('release:start', function () {
    hoo.log.info('release:start');
    var isDir = hoo.util.isDir(workCopy);
    if (isDir && del_flag) {
      //危险操作，要慎用
      hoo.log.info('删除' + workCopy + '目录下文件');
      hoo.util.del(workCopy);
    } else if (!isDir) {
      hoo.log.info('创建' + workCopy + '目录');
      hoo.log.info(workCopy);
      mkdirp(workCopy);
    }
  });

  hoo.on('release:end', function () {
    hoo.log.info('release:end\n');
  });

  hoo.on('deploy:start', function () {
    hoo.log.info('deploy:start');
  });

  hoo.on('deploy:end', function () {
    hoo.log.info('deploy:end');
    if(root=== '.'){
      return;
    }
    require('../../lib/submit')(root, settings.deployDir, false, deployMsg).then(function () {
      hoo.log.info('开始提交源码');
      var sourceSubmit = require('child_process').spawn(_.isWin() ? 'hoo.cmd' : 'hoo', ['submit', root, '-m', deployMsg]);
      // var sourceSubmit = require('child_process').spawn('node', ['./hoo/bin/hoo.js', 'submit', root, '-m', deployMsg]);
      sourceSubmit.stdout.on('data', function (data) {
        process.stdout.write(data);
      });
      sourceSubmit.stderr.on('data', function (data) {
        process.stdout.write(data);
      });
      sourceSubmit.on('close', function (code) {
        console.log('-------结束分割线-------');
      });
    });
  })
};
