

/*
TODO:
Add passport api tokens express middleware
Ability to restrict to https
Access other API interfaces from within an interface
*/

console.log("\nTapir starting:\n");

var express = require('express');
var bodyParser = require('body-parser');
var webdriver = require('selenium-webdriver');
var cheerio = require('cheerio');

var config = require('./api.js').config;
var apiInterfaces = require('./api.js').apiInterfaces;

var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

function register(interfaceName, apiInterface) {
  var driver;
  app.all(apiInterface.path, 
    function(req, res, next) {
      driver = new webdriver.Builder().
      withCapabilities(webdriver.Capabilities.chrome().set('chromeOptions', {args: ['--no-sandbox','--ignore-certificate-errors']})).
      build();
      next();
    }, 
    function(req, res, next) {
      console.log("Called " + interfaceName + " with query :" + JSON.stringify(req.query) + " params : " + JSON.stringify(req.params));
      next();
    },
    function(req, res, next) {
      apiInterface.method(req, res, webdriver, driver, cheerio);
      next();
    },
    function(req,res){
      driver.quit();
    });
}

for (var interfaceName in apiInterfaces) {
  var apiInterface = apiInterfaces[interfaceName];
  console.log("Registering " + interfaceName);
  register(interfaceName, apiInterface);
}

app.listen(config.apiPort);
console.log('\nTapir listening on port ' + config.apiPort + ' ...');
