/**
 * Copyright (c) 2014, Marco Grätsch <magdev3.0@gmail.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the <organization> nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */


var fs = require('fs'),
    path = require('path'),
    dateFormat = require('dateformat'),
    
    
    dateFormats = require(path.join(process.cwd(), 'config', 'date-format.json'));


/**
 * NodeResume Utils
 */
module.exports = exports = {


    /**
     * Update configuration with runtime settings
     *
     * @param config {Object}
     * @returns {Function}
     */
    updateConfig: function(config) {
        return function(req, res, next) {
            config.timeline.lang = req.i18n.getLocale();
            config.timeline.source = '/timeline.json';
            req.config = res.locals.config = config;
            return next();
        };
    },
    
    
    /**
     * Add Expires-Header
     * 
     * @param staticOptions {Object}
     * @returns {Function}
     */
    expires: function(staticOptions) {
        return function (req, res, next) {
            if (req.url.indexOf('/css/') === 0 
                    || req.url.indexOf('/js/') === 0 
                    || req.url.indexOf('/fonts/') === 0 
                    || req.url.indexOf('/icon/') === 0 
                    || req.url.indexOf('/img') === 0 
                    || req.url.indexOf('/images') === 0 
                    || req.url.indexOf('/me') === 0 
                    || req.url.indexOf('/favicon') === 0) {
                
                res.setHeader('Cache-Control', 'public, max-age=' + (staticOptions.maxAge/1000) + ', must-revalidate');
                res.setHeader('Expires', new Date(Date.now() + staticOptions.maxAge).toUTCString());
            } else if (req.url == '/') {
                res.setHeader('Cache-Control', 'no-cache');
                res.setHeader('Expires', new Date(Date.now()).toUTCString());
            }
            return next();
        };
    },
    
    
    /**
     * Set common headers
     * 
     * @param staticOptions {Object}
     * @returns {Function}
     */
    headers: function(staticOptions, isSSL) {
        isSSL = isSSL || false;
        return function(req, res, next) {
            res.setHeader('X-Frame-Options', 'deny');
            res.setHeader('X-XSS-Protection', '1; mode=block');
            res.setHeader('X-Content-Type-Options', 'nosniff');
            if (isSSL) {
                res.setHeader('Strict-Transport-Security', 'max-age=' + (staticOptions.maxAge/1000) + '; includeSubDomains');
            }
            return next();
        };
    },
    
    
    
    /**
     * Register the date formatter
     * 
     * @returns {Function}
     */
    dateFormatter: function() {
        return function(req, res, next) {
            var localeFormat = {
                names: dateFormat.i18n,
                format: 'yyyy-mm-dd'
            };
            
            var tmp = dateFormats[req.i18n.getLocale()] || null;
            if (tmp) {
                localeFormat = tmp;
                if (localeFormat.names) {
                    dateFormat.i18n = localeFormat.names;
                }
            }
            
            // Store the original dateFormat function
            req.dateFormat = res.locals.dateFormat = dateFormat;
            
            // Store the locale date settings
            req.localeFormat = res.locals.localeFormat = localeFormat;
            
            // Provide a formatter function
            req.date = res.locals.date = function(dateStr, format) {
                var date = new Date(dateStr.replace(',', '/'));
                format = format || req.localeFormat.format || 'yyyy-mm-dd';
                return req.dateFormat(date, format);
            };
            return next();
        };
    }
};