/* global describe, it, before, after */
var expect = require('must');
var virgilio = require('./');

describe('virgilio-cache tests', function() {
    var key = 'foo';
    var value = { bar: true };

    it('sets a key', function(done) {
        virgilio.cache.set(key, value)
            .then(function(newKey) {
                newKey.must.equal(key);
                done();
            })
            .catch(done);
    });

    it('gets a key', function(done) {
        virgilio.cache.get(key)
            .then(function(result) {
                result.must.eql(value);
                done();
            })
            .catch(done);
    });

    describe('it stores a value without setting a key', function() {
        var key = '';
        var value = 'bar';

        it('stores a value', function(done) {
            virgilio.cache.dump(value)
                .then(function(newKey) {
                    key = newKey;
                    done();
                })
                .catch(done);
        });

        it('gets a value', function(done) {
            virgilio.cache.get(key)
                .then(function(result) {
                    result.must.equal(value);
                    done();
                })
                .catch(done);
        });
    });

    describe('it sets a key with a timeout', function() {
        var key = '';
        var value = 'bar';

        before(function(done) {
            virgilio.cache.dump(value, 1)
                .then(function(newKey) {
                    key = newKey;
                    done();
                })
                .catch(done);
        });

        it('is available within the timeout period', function(done) {
            virgilio.cache.get(key)
                .then(function(result) {
                    result.must.equal(value);
                    done();
                })
                .catch(done);
        });

        it('is no longer available after the timout period', function(done) {
            setTimeout(function() {
                virgilio.cache.get(key)
                    .then(function(result) {
                        expect(result).be.null();
                        done();
                    })
                    .catch(done);
            }, 1500);
        });
    });

    after(function() {
        virgilio.redis.client$.end();
    });
});
