module("JSHint");

<%= "const JSHINT_OPTS = #{File.read(File.join(Rails.root, '.jshintrc'))};" %>

var qHint = function(name, sourceFile) {
    return asyncTestDiscourse(name, function() {
      if (typeof window.__jshintSrc !== "undefined") {
        var src = window.__jshintSrc[sourceFile];
        if (src) {
          start();
          qHint.validateFile(src, JSHINT_OPTS);
          return;
        }
      }
    });
};

qHint.validateFile = function (source, options, globals) {
  var i, len, err;

  source = source.replace(/^[^]*\/\/ IIFE Wrapped Content Begins:\n\n/m, "");
  source = source.replace(/\n\n\/\/ IIFE Wrapped Content Ends[^]*$/m, "");

  if (JSHINT(source, options, globals)) {
      ok(true);
      return;
  }

  for (i = 0, len = JSHINT.errors.length; i < len; i++) {
      err = JSHINT.errors[i];
      if (!err) {
          continue;
      }

      ok(false, err.reason +
          " on line " + err.line +
          ", character " + err.character);
  }
};

var XMLHttpFactories = [
  function () { return new XMLHttpRequest(); },
  function () { return new ActiveXObject("Msxml2.XMLHTTP"); },
  function () { return new ActiveXObject("Msxml3.XMLHTTP"); },
  function () { return new ActiveXObject("Microsoft.XMLHTTP"); }
];

function createXMLHTTPObject() {
  for (var i = 0; i < XMLHttpFactories.length; i++) {
      try {
          return XMLHttpFactories[i]();
      } catch (e) {}
  }
  return false;
}

// modified version of XHR script by PPK
// http://www.quirksmode.org/js/xmlhttp.html
// attached to qHint to allow substitution / mocking
qHint.sendRequest = function (url, callback) {
  var req = createXMLHTTPObject();
  if (!req) {
      return;
  }

  var method = "GET";
  req.open(method,url + "?" + (new Date().getTime()),true);
  req.onreadystatechange = function () {
      if (req.readyState != 4) {
          return;
      }

      callback(req);
  };

  if (req.readyState == 4) {
      return;
  }
  req.send();
};

<%
  TO_IGNORE = File.read("#{Rails.root}/.jshintignore").split("\n")

  def jshint(dir, remove)
    result = ""

    Dir.glob(dir).each do |f|
      filename = f.sub("#{Rails.root}/#{remove}", "")

      ok = true
      TO_IGNORE.each do |ig|
        ok = false unless (filename.index(ig.sub(remove, '')).nil?)
      end

      depend_on filename
      result << "qHint('#{filename}', '/assets/#{filename}', JSHINT_OPTS);\n" if ok

    end
    result
  end
%>

<%= jshint("#{Rails.root}/test/**/*.js", "test/javascripts/") %>
<%= jshint("#{Rails.root}/app/assets/javascripts/**/*.js", "app/assets/javascripts/") %>
<%= jshint("#{Rails.root}/app/assets/javascripts/**/*.es6", "app/assets/javascripts/") %>

