/*jshint esversion:6, node:true*/
'use strict';

const extend = require('gextend');

var DEFAULTS = {
    middleware: {
        use:   require('./middleware').use,
        order: require('./middleware').order,
    }
};

module.exports = function(options){

    return {
        init: function(context, config){

            config = extend({}, options, config);

            const express = require('express');
            var app = express();

            /*
             * Enable middleware to use context,
             * i.e. to publish an event system wide.
             * context.emit('web.request.createUser', user);
             */
            config.context = context;

            /*
             * Create a logger for our express app.
             * This can be trickled down to middleware
             * as well.
             */
             config.logger = context.getLogger(config.moduleid);

             /*
              * basedir will be used by middleware to
              * find the `public` directory, `views`,
              * etc...
              */
             if(!config.basedir){

                 if(!config.hasOwnProperty('moduleid')){
                     throw new Error('You need to specify "config.basedir". Else set "config.moduleid" so we can guess.');
                 }

                 let sep = require('path').sep;
                 config.basedir = [context.modulespath, config.moduleid].join(sep);

                 config.logger.warn('You did not specify a "basedir"?');
                 config.logger.warn('We are making a guess: %s', config.basedir);
             } else {
                 config.logger.warn('Loading views and assets from: %s', config.basedir);
             }

            setup(app, config);

            return app;
        }
    };
};

function setup(app, config){

    config = extend({}, DEFAULTS, config);

    var use = config.middleware.use;

    var order = config.middleware.order;

    order.map((middleware)=>{
        use[middleware](app, config);
    });
}

@@ -1067,33 +1067,32 @@
  */%0A            
- 
 if(!config.based
@@ -1093,25 +1093,24 @@
 .basedir)%7B%0A%0A
- 
             
@@ -1153,17 +1153,16 @@
 eid'))%7B%0A
- 
         
@@ -1283,37 +1283,35 @@
                 
- 
 %7D%0A%0A
- 
                 
@@ -1341,17 +1341,16 @@
 ').sep;%0A
- 
         
@@ -1433,33 +1433,32 @@
                 
- 
 config.logger.wa
@@ -1493,25 +1493,24 @@
 asedir%22?');%0A
- 
             
@@ -1570,33 +1570,32 @@
 onfig.basedir);%0A
- 
             %7D el
@@ -1607,33 +1607,32 @@
                 
- 
 config.logger.wa
@@ -1680,33 +1680,32 @@
 onfig.basedir);%0A
- 
             %7D%0A%0A 

fix formatting