"use strict";
/*
 * 针对.html、.htm文件，检索这些文件中引用的js、css的url 是否添加了 ‘?VERSION’ 字符串
 */

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

(function () {

  var chalk = require('chalk');
  var fs = require('fs');
  var table = require('text-table');
  var jsdom = require('jsdom').jsdom;
  var path = require('../../../utils/path.js');
  var url = require('url');

  var stReg = /('(\\.|[^\\'])*'|"(\\.|[^\\"])*")/ig;

  var trim = function trim(str) {
    return str.replace(/^"/, '').replace(/^'/, '').replace(/"$/, '').replace(/'$/, '');
  };

  var VersionString = function () {
    function VersionString() {
      _classCallCheck(this, VersionString);

      this.file = '';
      this.html = null;
      this.illSource = [];
      this.verString = 'VERSION';
    }

    _createClass(VersionString, [{
      key: '_reporter',
      value: function _reporter(messages, file) {

        var _this = this;

        if (!messages.length) {
          return;
        }
        var output = messages.map(function (message) {
          var out = [];
          out.push(message.type);
          out.push(message.uri);
          out.push(chalk.yellow('warning'));
          return out;
        });
        output = table(output, {
          align: ['r', 'l']
        });
        output = output.split('\n').map(function (el) {
          return el.replace(/(\d+)\s+(\d+)/, function (m, p1, p2) {
            return chalk.grey(p1 + ':' + p2);
          });
        }).join('\n');
        console.log('\n' + file + '\n');
        console.log(output);
        console.log(chalk.red.bold('\n✖ ' + messages.length + ' ill version string'));
      }
    }, {
      key: 'checkVer',
      value: function checkVer(repo, dirname, options, callback) {

        var _this = this;

        _this._setVersionString(options.string);

        _this.scanHtml(repo, dirname);

        if (_this.illSource.length > 0) {

          _this._reporter(_this.illSource, repo);
        }

        callback(null, _this.illSource);
      }
    }, {
      key: '_setVersionString',
      value: function _setVersionString(str) {
        if (str) {
          this.verString = str;
        }
      }
    }, {
      key: '_isIllVersion',
      value: function _isIllVersion(uri) {
        var _url = url.parse(uri);

        if (_url.host === null || _url.host.indexOf('h5.edaijia.cn') !== -1 || _url.host.indexOf('h5.d.edaijia.cn') !== -1) {
          if (_url.search && _url.search == '?' + this.verString) {
            return false;
          }
          return true;
        }

        return false;
      }
    }, {
      key: '_pushIllSource',
      value: function _pushIllSource(uri, type) {
        var _this = this;

        if (_this._isIllVersion(uri)) {

          _this.illSource.push({
            type: type,
            uri: uri
          });
        }
      }
    }, {
      key: '_domAnalyse',
      value: function _domAnalyse(window) {

        var _this = this;

        var $ = require('jquery')(window);

        _this.illSource = [];

        $("script").each(function () {
          if ($(this).attr('src')) {

            _this._pushIllSource($(this).attr('src'), 'js');
          } else {

            var script = $(this).text();
            var strings = script.match(stReg);

            strings && strings.map(function (str) {

              var _url = url.parse(trim(str));

              if (/\.js$/i.test(_url.pathname)) {

                _this._pushIllSource(trim(str), 'js');
              } else if (/\.css$/i.test(_url.pathname)) {

                _this._pushIllSource(trim(str), 'css');
              }
            });
          }
        });

        $("[rel=stylesheet]").each(function () {

          _this._pushIllSource($(this).attr('href'), 'css');
        });

        return _this.illSource;
      }
    }, {
      key: 'scanHtml',
      value: function scanHtml(repo, dirname, callback) {

        var _this = this;

        this.file = path.join(dirname, repo);

        this.html = fs.readFileSync(this.file, {
          encoding: 'utf8'
        });

        var doc = jsdom(this.html);
        var window = doc.defaultView;

        var $ = require('jquery')(window);

        _this._domAnalyse(window);

        window.close();

        /*jsdom.env(html, (error, window) => {
           let $ = require('jquery')(window);
           _this._domAnalyse(window, file);
           if (_this.illSource.length > 0) {
             _this._reporter(_this.illSource, repo);
           }
           window.close();
         });*/
      }
    }, {
      key: 'upVersion',
      value: function upVersion(repo, dirname, options, callback) {
        var _this2 = this;

        var _this = this;

        _this._setVersionString(options.string);

        _this.scanHtml(repo, dirname);

        if (_this.illSource.length > 0) {

          console.log(chalk.yellow('更新文件『' + repo + '』中js、css的VERSION String...'));

          _this.illSource.map(function (res) {
            var _uri = url.parse(res.uri);
            _uri.search = '?' + _this.verString;
            var _url = url.format(_uri);
            console.log(chalk.green(res.uri + ' to ' + _url));
            _this2.html = _this2.html.replace(res.uri, url.format(_url));
          });
        }

        fs.writeFileSync(_this.file, _this.html);

        callback(null, _this.illSource);
      }
    }]);

    return VersionString;
  }();

  module.exports = new VersionString();
})();