'use strict';

import express from 'express';
import OAuth2Server from 'oauth2-server';
import bodyParser from 'body-parser';
import {log} from './utils';
import Model from './oauth/twolevel.model.js';
// import throttle from './throttle/throttle.middleware.js';
import {userEncode} from './utils';

export default function createApp(config, tokenStore, userStore, configStore) {
  var app = express();

  app.oauth = OAuth2Server({
    model: new Model(tokenStore, userStore),
    grants: ['password'],
    debug: true
  });

  app.disable('x-powered-by');
  app.use(bodyParser.urlencoded({extended: true}));
  app.use(bodyParser.json());
  app.use(app.oauth.errorHandler());
  // app.use(throttle());

  app.get('/', function (req, res) {
    res.send('Helpful text about Smaug.');
  });

  app.get('/configuration', (req, res, next) => {
    var bearerToken = req.query.token;

    tokenStore.getAccessToken(bearerToken)
      .then(() => {
        configStore.get(bearerToken)
          .then((userConfig) => {
            res.send(JSON.stringify(userConfig, null, req.query.pretty ? 2 : null));
          })
          .catch((err) => {
            return next(err);
          });
      })
      .catch((err) => {
        return next(err);
      });
  });

  // Add implicit libraryId to anonymous user without libraryId, and change the password from accordingly.
  // The password must be equal to the username for an anonymous request, and userEncode(libraryId, null) returns the proper anonymous username/password for this
  app.use('/oauth/token', (req, res, next) => {
    if (req.body.username === userEncode(null, null)) {
      if (typeof config.defaultLibraryId === 'undefined') {
        log.error('No default library id. Set config.defaultLibraryId');
      }
      else {
        req.body.username += config.defaultLibraryId;
        if (req.body.password === userEncode(null, null)) {
          req.body.password += config.defaultLibraryId;
        }
      }
    }
    next();
  });
  app.post('/oauth/token', app.oauth.grant());

  return app;
}

@@ -297,231 +297,56 @@
 ';%0A%0A
-export default function createApp(config, tokenStore, userStore, configStore) %7B%0A  var app = express();%0A%0A  app.oauth = OAuth2Server(%7B%0A    model: new Model(tokenStore, userStore),%0A    grants: %5B'password'%5D,%0A    debug: true%0A  %7D
+function createBasicApp() %7B%0A  var app = express(
 );%0A%0A
@@ -376,16 +376,17 @@
 d-by');%0A
+%0A
   app.us
@@ -462,71 +462,8 @@
 ());
-%0A  app.use(app.oauth.errorHandler());%0A  // app.use(throttle());
 %0A%0A  
@@ -543,24 +543,187 @@
 .');%0A  %7D);%0A%0A
+  return app;%0A%7D%0A%0Aexport function createOAuthApp(config, tokenStore, userStore, configStore) %7B // eslint-disable-line no-unused-vars%0A  var app = createBasicApp();%0A%0A
   app.get('/
@@ -1180,16 +1180,374 @@
 %0A  %7D);%0A%0A
+  return app;%0A%7D%0A%0Aexport function createConfigurationApp(config, tokenStore, userStore, configStore) %7B // eslint-disable-line no-unused-vars%0A  var app = createBasicApp();%0A%0A  app.oauth = OAuth2Server(%7B%0A    model: new Model(tokenStore, userStore),%0A    grants: %5B'password'%5D,%0A    debug: true%0A  %7D);%0A%0A  app.use(app.oauth.errorHandler());%0A  // app.use(throttle());%0A%0A
   // Add
@@ -2321,28 +2321,319 @@
 .grant());%0A%0A  return app;%0A%7D%0A
+%0Aexport function createApp(config, tokenStore, userStore, configStore) %7B%0A  var app = express();%0A%0A  app.use(createConfigurationApp(config, tokenStore, userStore, configStore));%0A  app.use(createOAuthApp(config, tokenStore, userStore, configStore));%0A%0A  return app;%0A%7D%0A%0Aexport default createApp;%0A

split express app into oauth- and config parts