var debug   = require('debug')('static');
var fs      = require('fs');
var path  = require('path');

var DEBUG = process.env.DEBUG && (process.env.DEBUG != "undefined");

var STATIC_TYPES = {
    'css'   : 'text/css',
    'gif'   : 'image/gif',
    'html'  : 'text/html',
    'ico'   : 'image/x-icon',
    'jpeg'  : 'image/jpeg',
    'jpg'   : 'image/jpeg',
    'js'    : 'text/javascript',
    'json'  : 'application/json',
    'mp3'   : 'audio/mpeg',
    'pdf'   : 'application/pdf',
    'png'   : 'image/png',
    'svg'   : 'image/svg+xml',
    'swf'   : 'application/x-shockwave-flash',
    'tiff'  : 'image/tiff',
    'txt'   : 'text/plain',
    'wav'   : 'audio/x-wav',
    'wma'   : 'audio/x-ms-wma',
    'wmv'   : 'video/x-ms-wmv',
    'xml'   : 'text/xml'
};


exports = module.exports = function static(option) {

    option.absolutePath = fs.realpathSync('.') + path.sep + option.path;
    if (!option.maxAge) {
        option.maxAge = 7200;
    }

    return function(req, res, next) {

        var extension = req.url.match(/\.(\w+)$/);
        if(!extension || extension[1] == 'xsp' ){
            return next();
        }

        var filePath = option.absolutePath + req.url.replace(/\.\./ig, '');
        if(fs.existsSync(filePath)){
            fs.readFile(filePath, 'binary', function(err, file){
                if (err) {
                    throw err;
                } else {
                    if (DEBUG) debug('read static file:' + filePath + ' url:' + req.url);
                    var fileStat = fs.statSync(filePath);
                    var lastModified = fileStat.mtime.toUTCString();
                    var fileSize = fileStat.size;
                    if (req.headers['if-modified-since'] && lastModified == req.headers['if-modified-since']) {
                        res.writeHead(304, "Not Modified");
                        res.end();
                    } else {
                        try{


                        var contentType = STATIC_TYPES[extension[1]] || 'text/plain';
                        var expires = new Date(new Date().getTime() + option.maxAge * 1000).toUTCString();
                        var cacheControl = 'max-age=' + option.maxAge ;
                        var headers = {
                            'Content-Type'   : contentType,
                            'Expires'       : expires,
                            'Cache-Control' : cacheControl,
                            'Last-Modified' : lastModified
                        };
                        res.setHeader('Content-Length', fileSize);
                        res.writeHead( 200, headers );
                        }catch(e){
                        }

                        if (DEBUG) debug('http headers:{Cache-Control:' + cacheControl + '},{Content-Length:' + fileSize + '}');
                        res.write(file, 'binary');
                        res.end();
                    }
                }
            });

        } else {

            next();
        }
    };

};
