/**
 * Log middleware.
 * @function serverside.middleware.defineAccessLogMiddleware
 * @see {@link http://npmjs.org/package/connect-logger | connect-logger}
 * @param {object} context - Server context object.
 * @param {string} context.ACCESS_LOG_PATH - Log file name.
 * @param {string} context.ACCESS_LOG_FORMAT - Log format name.
 * @return {object} - A new logger.
 * @author Taka Okunishi
 *
 */
var log = require('../../lib/log'),
    path = require('path'),
    apeman = require('apeman'),
    FileLogger = log.FileLogger;


exports = module.exports = function (context) {
    context.assertKeys(['ACCESS_LOG_PATH', 'ACCESS_LOG_FORMAT']);

    var filename = context.ACCESS_LOG_PATH,
        logger = exports._connectLogger(
            exports._tokens,
            exports._formats
        );
    return logger({
            stream: new FileLogger().filename(filename)._stream,
            format: context.ACCESS_LOG_FORMAT
        }
    );
};

exports._connectLogger = function (tokens, formats) {
    var connect = require('connect'),
        logger = connect.logger;
    Object.keys(tokens).forEach(function (name) {
        logger.token(name, tokens[name]);
    });
    Object.keys(formats).forEach(function (name) {
        logger.format(name, formats[name]);
    });
    return logger;
};

exports._formats = {
    a: ':remote-addr - - [:local-date] (process :pid) ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent" "apeman-id=:apeman-id"- :response-time ms'
};

exports._tokens = {
    'local-date': function () {
        return new Date().toLocaleString();
    },
    'pid': function () {
        return process.pid;
    },
    'apeman-id': function (req) {
        return req.apemanId && req.apemanId() || 'null';
    }
};