'use strict'

var staticContent = require('node-static'),
	url = require('url'),
	path = require('path');

var StaticContentHandler = function(rootContext, descriptor) {
	this.rootContext = rootContext;
	this.server = new staticContent.Server(descriptor.path);
	this.descriptor = descriptor;
};

StaticContentHandler.prototype.handle = function(req, res, usr) {
    var handler = this,
        pathname;

    var finish = function (status, headers) {
        handler.server.finish(status, headers, req, res);
    };

    try {
        pathname = decodeURI(url.parse(req.url).pathname)
        	.substr(this.rootContext.length + this.descriptor.name.length);
    }
    catch(e) {
        return process.nextTick(function() {
            return finish(400, {});
        });
    }

    process.nextTick(function () {
        handler.server.servePath(pathname, 200, {}, req, res, finish);
    });
};

module.exports = StaticContentHandler;