var http = require('http');
var debug = require('debug')('xserver');

module.exports = createServer;

function createServer() {

    var server = function server(req, res, out) {
        var index = 0;
        var stack = server.stack;

        //simple remove request domain
        var offset = req.url.indexOf('//');
        if (offset != -1){
            var part = req.url.substr(offset + 2);
            req.url = part.substr(part.indexOf('/'));
        }
        var next = function() {
            var handler = stack[index++];
            if (!handler) {
                return;
            }

            handler(req, res, next);
        };

        next();
    };

    server.stack = [];

    server.use = function(fn) {
        this.stack.push(fn);
        return this;
    };

    server.listen = function() {
        var httpServer = http.createServer(this);
        httpServer.listen.apply(httpServer, arguments);
    };

    return server;
}

