/**
 * File logger.
 * @augment lib.log.Logger
 * @constructor lib.log.FileLogger
 * @param {string} level - Log level.
 * @author Taka Okunishi
 *
 */
var fs = require('fs'),
    file = require('../file'),
    object = require('../object'),
    _prototype = require('./_prototype'),
    Logger = _prototype.Logger,
    levels = _prototype.levels ,
    define = object.define;


exports = module.exports = define({
    prototype: Logger,
    accessor: [
    /**
     * Log file name.
     * @name lib.log.FileLogger
     * @function
     * @param {string} filename - Log file name.
     */
        'filename'
    ],
    /** @lends lib.log.FileLogger.prototype **/
    properties: {
        filename: function (filename) {
            var s = this;
            s._filename = filename;
            if (filename) {
                s._stream && s._stream.end();
                s._stream = fs.createWriteStream(filename, {
                    flags: 'a'
                });
            }
            return s;
        },
        _write: function (msg, level) {
            var s = this;
            var prefix = '[' + s._now() + ']' + '[' + exports._levelString(level) + ']';
            s._stream.write([prefix, msg].join(' ') + '\n');
        },
        _err: function (msg, level) {
            var s = this;
            Logger.prototype._err.apply(s, arguments);
            s._write(msg, level);
        },
        _log: function (msg, level) {
            var s = this;
            Logger.prototype._log.apply(s, arguments);
            s._write(msg, level);
        },
        kill: function () {
            var s = this;
            s._stream && s._stream.end();
        },
        _now: function () {

            return new Date().toString();
        }
    }
});
exports._levelString = function (level) {
    for (var key in levels) {
        if (!levels.hasOwnProperty(key)) continue;
        var hit = levels[key] === level;
        if (hit) return key;
    }
    return "";
};