// hoo release dev 开发环境测试
var path = require('path');
var requirejs = require('requirejs');
var _ = require('../../lib/util');
var server_util = require('fis3-command-server/lib/util');
var settings = require('../settings');
var dev_ip = require('dev-ip')()[0];
module.exports = function (hoo, root, port) {
  var server_port = port || settings.port;
  var _initilized = false;
  var lastModifedHtmlFiles = {};
  hoo.media('dev')
    .match('**', {
      useCache: true
    })
    .match('**.js', {
      useHash: false
    })
    .match('**', {
      deploy: [
        hoo.plugin('skip-packed', {
          // 配置项
          skipPackedToPkg: true,//是否过滤掉被打包的文件
          skipPackedToAIO: true,//是否过滤掉被 AllInOne 打包的文件
          skipPackedToCssSprite: true,//是否过滤掉被 css sprite 合并的文件。
          ignore: []//即便设置了过滤，但是如果目标文件 ignore 列表中，还是不会被过滤。glob 语法，数组或者字符串。
        }),
        function (options, modified, total, next) {
          var rLivereload = /"(?:[^\\"\r\n\f]|\\[\s\S])*"|'(?:[^\\'\n\r\f]|\\[\s\S])*'|(<\/body>|<!--livereload-->)/ig;
          var i = modified.length - 1;
          var file;
          while ((file = modified[i--])) {
            if (file.isHtmlLike) {
              (_initilized && (lastModifedHtmlFiles[file.subpath] && (lastModifedHtmlFiles[file.subpath]._md5 === hoo.util.md5(file._content, 32)))) ? modified.splice(i + 1, 1) : file.setContent(file.getContent().replace(rLivereload, function (all, token) {
                  lastModifedHtmlFiles[file.subpath] = {
                    _md5: hoo.util.md5(file._content, 32)
                  };
                  if (token) {
                    all = '<script type="text/javascript" charset="utf-8" src="http://' + dev_ip + ':' + settings.browserSyncPort + '/browser-sync/browser-sync-client.2.15.0.js"></script>' + token;
                  }
                  return all;
                }));
            }
          }
          _initilized = true;
          next();
        },
        hoo.plugin('local-deliver', {
          to: path.join(settings.sourceDir, root, '.hoo_cache')
        })
      ]
    });

  var releaseFirstTime = true;
  hoo.on('release:end', function () {
    var newPath = path.join(process.cwd(), settings.sourceDir, root, settings.devTmpDir);
    if (releaseFirstTime) {
      releaseFirstTime = false;
      var browserSync = require('browser-sync').create();
      var bs = browserSync.init({
        port: settings.browserSyncPort,
        open: false,
        socket: {
          domain: '127.0.0.1:'+settings.browserSyncPort
        },
        files: [
          path.join(newPath, '**/*.css'),
          path.join(newPath, '**/*.png'),
          path.join(newPath, '**/*.jpg'),
          path.join(newPath, '**/*.js'),
          path.join(newPath, '**/*.html'),
          {
            match: [path.join(newPath, 'mock/server.conf')],
            fn: function (event, file) {
            }
          }, {
            match: [path.join(process.cwd(), settings.sourceDir, root, 'components/config/config.js')],
            fn: function (event, file) {
              try {
                requirejs.undef(file);
                var apiUrl = requirejs(file).apiUrl;
                require('../../lib/parseText')(path.join(process.cwd(), settings.sourceDir, root, 'mock/server.conf'), function (res) {
                  for (var key in apiUrl) {
                    if (typeof res[key] === 'undefined') {
                      res[key] = {
                        type: 'proxy',
                        path: apiUrl[key]
                      }
                    } else if (res[key].type === 'proxy') {
                      res[key].path = apiUrl[key];
                    }
                  }

                  var result = '';
                  for (var key in apiUrl) {
                    result += res[key].type + ' ^\\\/' + key + ' ' + res[key].path + '\n';
                  }
                  require('fs').writeFile(path.join(process.cwd(), settings.sourceDir, root, 'mock/server.conf'), result, function (err) {
                    if (err) {
                      hoo.log.error(err);
                    }
                  });
                  hoo.log.info("mock配置已更改");
                });
              } catch (e) {
                hoo.log.error(e);
              }
            }
          }],
        scriptPath: function (path) {
          return "localhost:" + settings.browserSyncPort + path;
        },
        script: {
          domain: '127.0.0.1:' + settings.browserSyncPort
        },
        logFileChanges: true,
        logSnippet: false
      }, function (err) {
        if (err) {
          hoo.log.error(err);
          return;
        }
        var bsPort = bs.options.get('port');
        if (bsPort !== settings.browserSyncPort) {
          hoo.log.error("您的本机端口" + settings.browserSyncPort + "已被占用，hoo暂无法使用，请关掉相关进程后重试!");
          process.exit();
        }

        var spawn_server = require('child_process').spawn(_.isWin() ? 'hoo.cmd' : 'hoo', ['server', 'start', '-p', server_port, '--no-daemon', /* '--no-browse', */'--root', newPath]);
        spawn_server.stdout.on('data', function (data) {
        });
        spawn_server.stderr.on('data', function (data) {
        });
        spawn_server.on('close', function (code) {
          hoo.log.error('web服务器异常，已关闭');
          process.exit();
        });
      });
    }
  });
};
