
var cobs = require('../..'),
    http = require('http'),
    url = require('url'),
    fs = require('fs');

function getPage(filename) {
    var program = cobs.compileTemplateFile(filename);
    return function (req, res) {
        program.run(cobs.getRuntime({ request: req, response: res, require: require }));
    }
}
var program = cobs.compileTemplateFile('./databases.cobp');

var mapping = {};

mapping['/'] = getPage('./databases.cobp');
mapping['/database'] = getPage('./database.cobp');
mapping['/table'] = getPage('./table.cobp');

// Tricky code, to review, put require in runtime
global.require = require;

http.createServer(function(req, res) {
    var requrl = url.parse(req.url, true);
    var page = mapping[requrl.pathname];
    req.params = requrl.query;
    
    if (page)
        page(req,res);
    else {
        res.writeHead(404, { 'Content-type': 'text/plain' });
        res.end("bad URL " + req.url);
    }
}).listen(8000);

console.log('Server started, listening at port 8000');