var bodyParser = require('body-parser');
var cliHelper = require('./cliHelper');
var elementExplorerClient = require('./elementExplorerClient');
var express = require('express');
var locatorFinder = require('./locatorFinder');

var startExpress = function() {
  var app = express();
  app.use(bodyParser.json());

  var encode = function(results) {
    return {results: results};
  };

  app.get('/testSelector', function(req, res) {
    var query = req.query;

    if (query.popupInput) {
      return handlePopupRequest(query.popupInput, res);
    }

    if (query.locators) {
      return handleDevTools(query.locators, res);
    }

    res.send(encode({error: 'Invalid input'}));
  });

  function handlePopupRequest(input, res) {
    // If the popup input starts with 'by' then execute a count expression.
    if (/^by/.test(input)) {
      input = 'element.all(' + input + ').count()';
    }

    console.log('Popup input [%s]', input);

    elementExplorerClient.runCommand(input).then(function(response) {
      var results = {};
      results[input] = response;

      res.send(encode(results));
    });
  }

  function handleDevTools(devtoolsInput, res) {
    var locatorResults = {},
        locators = JSON.parse(devtoolsInput),
        suggestionList = locatorFinder.buildLocatorList(locators);

    console.log('Testing suggestions', suggestionList);

    function testNext(index) {
      // Is it done testing locators?
      if (index === suggestionList.length) {
        console.log('Done testing suggestions, returning', locatorResults);
        return res.send(encode(locatorResults));
      }

      var suggestion = suggestionList[index],
          input = suggestion.countExpression;
      elementExplorerClient.runCommand(input).then(function(response) {
        locatorResults[suggestion.locator] = response;
        testNext(index + 1);
      });
    }
    testNext(0);
  }

  var server = app.listen(13000, function() {
    console.log('Elementor is listening on http://localhost:%s',
        server.address().port);
  });
};

var startServer = function() {
  cliHelper.startProtractor().then(function() {
    console.log('Done starting protractor');
    startExpress();
  });
};

module.exports = {
  start: startServer
};

@@ -79,23 +79,16 @@
 );%0Avar e
-lementE
 xplorerC
@@ -127,24 +127,24 @@
 erClient');%0A
+
 var express 
@@ -931,31 +931,24 @@
 put);%0A%0A    e
-lementE
 xplorerClien
@@ -1692,23 +1692,16 @@
 %0A      e
-lementE
 xplorerC
@@ -2025,16 +2025,82 @@
 %7D);%0A%7D;%0A%0A
+/** Start protractor process, then start the elementor server. */%0A
 var star
@@ -2100,22 +2100,16 @@
 ar start
-Server
  = funct
@@ -2258,16 +2258,16 @@
 rts = %7B%0A
+
   start:
@@ -2276,14 +2276,8 @@
 tart
-Server
 %0A%7D;%0A

Rename some internal variables