/* jshint -W097 */// jshint strict:false
/*jslint node: true */
var expect = require('chai').expect;
var setup  = require(__dirname + '/lib/setup');

var objects = null;
var states  = null;
var onStateChanged = null;
var onObjectChanged = null;
var sendToID = 1;

var adapterShortName = setup.adapterName.substring(setup.adapterName.indexOf('.')+1);

function checkConnectionOfAdapter(cb, counter) {
    counter = counter || 0;
    console.log('Try check #' + counter);
    if (counter > 30) {
        if (cb) cb('Cannot check connection');
        return;
    }

    console.log('Checking alive key for key : ' + adapterShortName);
    states.getState('system.adapter.' + adapterShortName + '.0.alive', function (err, state) {
        if (err) console.error(err);
        if (state && state.val) {
            if (cb) cb();
        } else {
            setTimeout(function () {
                checkConnectionOfAdapter(cb, counter + 1);
            }, 1000);
        }
    });
}

function checkValueOfState(id, value, cb, counter) {
    counter = counter || 0;
    if (counter > 20) {
        if (cb) cb('Cannot check value Of State ' + id);
        return;
    }

    states.getState(id, function (err, state) {
        if (err) console.error(err);
        if (value === null && !state) {
            if (cb) cb();
        } else
        if (state && (value === undefined || state.val === value)) {
            if (cb) cb();
        } else {
            setTimeout(function () {
                checkValueOfState(id, value, cb, counter + 1);
            }, 500);
        }
    });
}

function sendTo(target, command, message, callback) {
    onStateChanged = function (id, state) {
        if (id === 'messagebox.system.adapter.test.0') {
            callback(state.message);
        }
    };

    states.pushMessage('system.adapter.' + target, {
        command:    command,
        message:    message,
        from:       'system.adapter.test.0',
        callback: {
            message: message,
            id:      sendToID++,
            ack:     false,
            time:    (new Date()).getTime()
        }
    });
}

describe('Test ' + adapterShortName + ' adapter', function() {
    before('Test ' + adapterShortName + ' adapter: Start js-controller', function (_done) {
        this.timeout(600000); // because of first install from npm

        setup.setupController(function () {
            var config = setup.getAdapterConfig();
            // enable adapter
            config.common.enabled  = true;
            config.common.loglevel = 'debug';

            //config.native.dbtype   = 'sqlite';

            setup.setAdapterConfig(config.common, config.native);

            setup.startController(true, function(id, obj) {}, function (id, state) {
                    if (onStateChanged) onStateChanged(id, state);
                },
                function (_objects, _states) {
                    objects = _objects;
                    states  = _states;
                    _done();
                });
        });
    });

    it('Test ' + adapterShortName + ' adapter: Check if adapter started', function (done) {
        this.timeout(60000);
        checkConnectionOfAdapter(function (res) {
            if (res) console.log(res);
            expect(res).not.to.be.equal('Cannot check connection');
            objects.setObject('system.adapter.test.0', {
                    common: {

                    },
                    type: 'instance'
                },
                function () {
                    states.subscribeMessage('system.adapter.test.0');
                    objects.getObject('system.adapter.history.0.memRss', function (err, obj) {
                        obj.common.custom = {
                            'history.0': {
                                enabled:      true,
                                changesOnly:  false,
                                debounce:     0,
                                retention:    31536000,
                                maxLength:    3
                            }
                        };
                        objects.setObject('system.adapter.history.0.memRss', obj, function (err) {
                            // wait till adapter receives the new settings
                            setTimeout(function () {
                                done();
                            }, 2000);
                        });
                    });
                });
        });
    });
    it('Test ' + adapterShortName + ': Write values into DB', function (done) {
        this.timeout(25000);
        var now = new Date().getTime();

        states.setState('system.adapter.history.0.memRss', {val: 1, ts: now - 2000}, function (err) {
            if (err) {
                console.log(err);
            }
            setTimeout(function () {
                states.setState('system.adapter.history.0.memRss', {val: 2, ts: now - 1000}, function (err) {
                    if (err) {
                        console.log(err);
                    }
                    setTimeout(function () {
                        states.setState('system.adapter.history.0.memRss', {val: 3, ts: now}, function (err) {
                            if (err) {
                                console.log(err);
                            }
                            setTimeout(function () {
                                sendTo('history.0', 'getHistory', {
                                    id: 'system.adapter.history.0.memRss',
                                    options: {
                                        end:       now,
                                        count:     50,
                                        aggregate: 'onchange'
                                    }
                                }, function (result) {
                                    console.log(JSON.stringify(result.result, null, 2));
                                    expect(result.result.length).to.be.at.least(3);
                                    var found = 0;
                                    for (var i = 0; i < result.result.length; i++) {
                                        if (result.result[i].val >= 1 && result.result[i].val <= 3) found ++;
                                    }
                                    expect(found).to.be.equal(3);
                                    done();
                                });
                            }, 100);
                        });
                    }, 100);
                });
            }, 100);
        });
    });

    after('Test ' + adapterShortName + ' adapter: Stop js-controller', function (done) {
        this.timeout(10000);

        setup.stopController(function (normalTerminated) {
            console.log('Adapter normal terminated: ' + normalTerminated);
            done();
        });
    });
});

@@ -5328,65 +5328,8 @@
   %7D%0A
-                            setTimeout(function () %7B%0A    
     
@@ -5416,28 +5416,24 @@
             
-   
- 
 id: 'system.
@@ -5459,20 +5459,16 @@
 emRss',%0A
-    
         
@@ -5538,20 +5538,16 @@
         
-    
 end:    
@@ -5590,20 +5590,16 @@
         
- 
-   
 count:  
@@ -5605,20 +5605,16 @@
     50,%0A
-    
         
@@ -5691,34 +5691,26 @@
             
-  
-  %7D%0A    
+%7D%0A
             
@@ -5744,28 +5744,24 @@
  (result) %7B%0A
-    
             
@@ -5857,36 +5857,32 @@
                 
-    
 expect(result.re
@@ -5941,28 +5941,24 @@
             
-    
 var found = 
@@ -5992,20 +5992,16 @@
         
-  
-  
 for (var
@@ -6037,28 +6037,24 @@
 gth; i++) %7B%0A
-    
             
@@ -6147,20 +6147,16 @@
 und ++;%0A
-    
         
@@ -6209,28 +6209,24 @@
             
-    
 expect(found
@@ -6267,36 +6267,32 @@
                 
-    
 done();%0A        
@@ -6315,50 +6315,9 @@
     
-  
-  %7D);%0A                            %7D, 100
+%7D
 );%0A 

enhance testing