/*官网开发配置*/
var path = require('path');
var settings = require('../settings');
var _ = require('../../lib/util');
var dev_ip = require('dev-ip')()[0];
module.exports = function (hoo, root, media, port) {
  var server_port = port || settings.port;
  var projectFiles = hoo.get('project.files');
  projectFiles.pop();
  projectFiles.pop();
  projectFiles.pop();
  projectFiles.push('/opening/*.html');
  hoo.set('project.files', projectFiles);
  // 设置占位符
  var query = '?v=' + Date.now();
  var defineConfig = {};
  var _initilized = false;
  var lastModifedHtmlFiles = {};

  hoo.media(media, defineConfig).match('**', {
    useHash: false,
    useCache: true
  })
    .match('/opening/*.html', {
      isInline: false,
      release: '$0'
    })
    .match('**.png', {
      optimizer: hoo.plugin('png-compressor', {
        // pngcrush or pngquant
        // default is pngcrush
        type: 'pngquant'
      })
    })
    .match('::package', {
      packager: hoo.plugin('map', {
        useTrack: false// 是否输出路径信息,默认为 true
      }),
      // 分析 __RESOURCE_MAP__ 结构，来解决资源加载问题
      postpackager: hoo.plugin('loader', {
        resourceType: 'amd',
        useInlineMap: true
      }, 'prepend')
    })
    .match('**', {
      deploy: [
        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.wwwSourceDir, root, settings.devTmpDir)
        })
      ]
    });

  var releaseFirstTime = true;

  hoo.on('release:end', function (ret) {
    var child_process = require('child_process');
    if (releaseFirstTime) {
      var newPath = path.join(process.cwd(), settings.wwwSourceDir, root, settings.devTmpDir);
      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')
        ],
        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;
        }
        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();
        });

      });
      hoo.log.info('----------browserSync进程启动-----------');
    }
  });
};
