
/*jslint vars: true, node: true */
"use strict";

var fs = require('fs');
var path = require('path');
var cache = require('../cache');
var imsServiceTokenUtils = require('../utils').imsServiceTokenUtils;


var mimeMap = {
    '.txt': 'text/plain',
    '.html': 'text/html',
    '.htm': 'text/html',
    '.css': 'text/css',
    '.xml': 'application/xml',
    '.json': 'application/json',
    '.js': 'application/javascript',
    '.jpg': 'image/jpeg',
    '.jpeg': 'image/jpeg',
    '.gif': 'image/gif',
    '.png': 'image/png',
    '.woff': 'application/font-woff',
    '.svg': 'image/svg+xml'
};

var WEB_APP_PATH = "/public";
var WELCOME_PAGE = "index.html";

function serveStaticContent(req, res, next) {
    //console.log('@staticHandler: serving ' + req.url);

    var filePath = '.' + WEB_APP_PATH + req.url;
    if (filePath === '.' + WEB_APP_PATH + "/") {
        filePath = '.' + WEB_APP_PATH + '/' + WELCOME_PAGE; // Default page (welcome page)
    }

    // Get rid of request paramaters if any
    filePath = filePath.split("?")[0];
    var extname = path.extname(filePath);
    var contentType = mimeMap[extname] || 'text/html';
    
    fs.stat(filePath, function (err, stats) {
        if (!err && stats.isFile()) {
            var content = cache.get(filePath, {'type': 'file'});
            res.cache("no-Cache");
            res.writeHead(200, {'Content-Type': contentType});
            res.end(content, 'utf-8');
        } else if (!err && stats.isDirectory()) {
            res.header('Location', '/');
            res.send(302);
        } else {
            res.send(404);
        }
    });
}

function addPrivateCaching(req, res, next) {
    res.header('Cache-control', 'private');
    next();
}

module.exports = {
    handleStaticContent : serveStaticContent,
    addPrivateCaching : addPrivateCaching
};
