let assert = require('assert');
import Logger from '../logger';
import Utils from '../utils';
import Settings from "../settings";

let config = {
    outputFile: "output" , 
    errorFile: "errors",
    logFolder: "logs",
    rotatingSize: "1M",
    logLevel: Logger.LOG_LEVEL.DEBUG,
    debugLogging: false
}

class CustomLogger extends Logger {
    public outputWrite(write: (chunk: any, encoding?: string, cb?: Function) => boolean){ 
        this.outputStream.write = write;
    }
    public errorWrite(write: (chunk: any, encoding?: string, cb?: Function) => boolean){
        this.errorStream.write = write;
    }
} 

describe('test logger', function () {
    let oldLog:(message?: any, ...optionalParams: any[])=> void;
    let oldConf: Object;

    beforeEach(function() {
        oldLog = console.log;
        oldConf = Utils.deepExtend({}, config);
    });

    afterEach(function() {
        console.log = oldLog;
        config = Utils.deepExtend({}, oldConf);
    });

    it('general log', function (done) {
        Settings.Instance.setLogger("test", config);
        let logger = new CustomLogger("test");


        logger.outputWrite(function(str: string){
            assert.notEqual(str.indexOf("[DEBUG]"), -1);
            assert.notEqual(str.indexOf("message"), -1); 
            done();        
            return true;   
        });
        logger.errorWrite(function(str: string){
            done("no need to log in error file");   
            return true;   
            
        });
        logger.log("message", Logger.LOG_LEVEL.DEBUG);
    });

    it('error log', function (done) {
        config.logLevel = 0; //error need to log always

        Settings.Instance.setLogger("test", config);
        let logger = new CustomLogger("test");

        logger.errorWrite(function(str){
            assert.notEqual(str.indexOf("[ERROR]"), -1);
            assert.notEqual(str.indexOf("message"), -1);
            done();  
            return true;                      
        });
        logger.outputWrite(function(str){
            done("no need to log in output file");
            return true; 
        });
        logger.log("message", Logger.LOG_LEVEL.ERROR);
    });

    it('debug log', function (done) {
        console.log = function(str: string){
            console.log = oldLog;
            assert.notEqual(str.indexOf("[DEBUG]"), -1);
            assert.notEqual(str.indexOf("message"), -1);
            done();
        }
        config.debugLogging = true;

        Settings.Instance.setLogger("test", config);
        let logger = new CustomLogger("test");
        logger.outputWrite(function(str){
            done("no need to log in output file");
            return true; 
        });
        logger.errorWrite(function(str){
            done("no need to log in error file");  
            return true;           
        });
        logger.log("message", Logger.LOG_LEVEL.DEBUG);
    });
});