var BaseRollingFileStream = require('./BaseRollingFileStream'),
    format = require('../date_format'),
    async = require('async'),
    fs = require('fs'),
    util = require('util');

module.exports = DateRollingFileStream;

function debug(message) {
//    console.log(message);
}

function DateRollingFileStream(filename, pattern, options, now) {
    debug("Now is " + now);
    if (pattern && typeof(pattern) === 'object') {
        now = options;
        options = pattern;
        pattern = null;
    }
    this.pattern = pattern || '.yyyy-MM-dd';
    this.now = now || Date.now;
    this.lastTimeWeWroteSomething = format.asString(this.pattern, new Date(this.now()));
    debug("this.now is " + this.now + ", now is " + now);

    DateRollingFileStream.super_.call(this, filename, options);
    this.rollBeforeWrite = true;
}

util.inherits(DateRollingFileStream, BaseRollingFileStream);

DateRollingFileStream.prototype.shouldRoll = function() {
    var lastTime = this.lastTimeWeWroteSomething,
        thisTime = format.asString(this.pattern, new Date(this.now()));

    debug("DateRollingFileStream.shouldRoll with now = " + this.now() + ", thisTime = " + thisTime + ", lastTime = " + lastTime);

    this.lastTimeWeWroteSomething = thisTime;
    this.previousTime = lastTime;

    return thisTime !== lastTime;
};

DateRollingFileStream.prototype.roll = function(filename, callback) {
    var that = this,
        newFilename = filename + this.previousTime;

    debug("Starting roll");
    debug("Queueing up data until we've finished rolling");
    debug("Flushing underlying stream");
    this.flush();

    async.series([
        deleteAnyExistingFile,
        renameTheCurrentFile,
        openANewFile
    ], callback);

    function deleteAnyExistingFile(cb) {
        //on windows, you can get a EEXIST error if you rename a file to an existing file
        //so, we'll try to delete the file we're renaming to first
        fs.unlink(newFilename, function (err) {
            //ignore err: if we could not delete, it's most likely that it doesn't exist
            cb();
        });
    }

    function renameTheCurrentFile(cb) {
        debug("Renaming the " + filename + " -> " + newFilename);
        fs.rename(filename, newFilename, cb);
    }

    function openANewFile(cb) {
        debug("Opening a new file");
        fs.open(
            filename,
            that.options.flags,
            that.options.mode,
            function (err, fd) {
                debug("opened new file");
                var oldLogFileFD = that.fd;
                that.fd = fd;
                that.writable = true;
                fs.close(oldLogFileFD, cb);
            }
        );
    }


};
