'use strict';

var cleanBaseURL = require('clean-base-url');
var existsSync = require('exists-sync');
var path = require('path');
var fs = require('fs');

function TestsServerAddon(project) {
  this.project = project;
  this.name = 'tests-server-middleware';
}

TestsServerAddon.prototype.serverMiddleware = function(config) {
  var app = config.app;
  var options = config.options;
  var watcher = options.watcher;

  var baseURL = cleanBaseURL(options.baseURL);
  var testsRegexp = new RegExp('^' + baseURL + 'tests');

  app.use(function(req, res, next) {
    watcher.then(function(results) {
      var acceptHeaders = req.headers.accept || [];
      var hasHTMLHeader = acceptHeaders.indexOf('text/html') !== -1;
      var hasWildcardHeader = acceptHeaders.indexOf('*/*') !== -1;

      var isForTests = testsRegexp.test(req.path);

      if (isForTests && (hasHTMLHeader || hasWildcardHeader) && req.method === 'GET') {
        var assetPath = req.path.slice(baseURL.length);
        var filePath = path.join(results.directory, assetPath);

        if(!existsSync(filePath) || !fs.lstatSync(filePath).isFile()) {
          req.url = baseURL + '/tests/index.html';
        }
      }

    }).finally(next).finally(function() {
      if (config.finally) {
        config.finally();
      }
    });
  });
};

module.exports = TestsServerAddon;

@@ -146,16 +146,71 @@
 e('fs');
+%0Avar debug = require('debug')('ember-cli:serve-files');
 %0A%0Afuncti
@@ -881,24 +881,68 @@
 req.path);%0A%0A
+      debug('isForTests: %25o', isForTests);%0A%0A
       if (is
@@ -1261,16 +1261,217 @@
 .html';%0A
+          var newURL = baseURL + '/tests/index.html';%0A%0A          debug('url: %25s resolved to path: %25s which is not a file. Assuming %25s instead', req.path, filePath, newURL);%0A          req.url = newURL;%0A
         

add logging for tests-server middleware