"use strict";
/**
 * 1、检索当前目录下的所有文件（src, node_modules除外）。
 * 2、找到.html、.htm等文件，给这样文件中引用的js、css的url后添加 ‘?VERSION’ 字符串
 */

(function () {

  var async = require('async');
  var chalk = require('chalk');
  var path = require('../../utils/path.js');
  var walk = require('../../utils/walk.js');

  var ver = require('./utils/ver.js');

  var singleFile = function singleFile(file, dirname, isReplace, options) {
    var illLength = 0;

    if (file) {

      if (isReplace) {

        ver.upVersion(file, dirname, options, function (error, illSource) {
          illLength += illSource ? illSource.length : 0;
        });
      } else {

        ver.checkVer(file, dirname, options, function (error, illSource) {
          illLength += illSource ? illSource.length : 0;
        });
      }
    }

    return illLength;
  };

  module.exports = function (options) {

    var isReplace = options.replace || false;

    if (isReplace) {

      console.log('\n添加/替换VERSION String...');
    } else {

      console.log('\n检查VERSION String...');
    }

    if (options.file) {

      var dirname = options.file.toString().match(/^\//) ? "/" : process.cwd();

      singleFile(options.file, dirname, isReplace, options);
    } else {
      (function () {

        var dirname = options.dir ? options.dir.match(/^\//) ? options.dir : path.join(process.cwd(), options.dir) : process.cwd();

        var regIncludes = [/\.(x|s|d)?html?$/i];

        var regExcludes = [/node_modules/, /\.git/, /\.tmp/];

        walk(dirname, regIncludes, regExcludes, function (err, results) {

          if (err) {
            throw err;
          }

          var illLength = 0;

          async.each(results, function (repo, callback) {

            var suffix = path.extname(repo).slice(1);

            if (suffix == 'jade') {

              console.log('jade');
            } else {

              illLength += singleFile(repo.replace(dirname, ""), dirname, isReplace, options);
            }

            callback();
          }, function () {
            if (illLength == 0) {
              console.log(chalk.green('虽然不想承认，但是真没找到需要添加/替换VERSION String的文件...'));
            }
          });
        });
      })();
    }
  };
})();