var http = require('http');

describe('Server', function(){

    var Server = null;

    it('require Server', function(){
    	Server = require('../../lib/index.js').Net.Server;
    	expect(Server).toBeTruthy();

        beforeEach(function(){
            Server = require('../../lib/index.js').Net.Server;
        });
	});

    describe('Server instance', function() {
        var callback;
        var instance;
        var serverMock;

        beforeEach(function() {
            Server = require('../../lib/index.js').Net.Server;
            callback = jasmine.createSpy('callback');
            instance = new Server();
            serverMock = jasmine.createSpyObj('nativeServer', ['listen', 'listenFD']);

            spyOn(instance, '_reattachListeners').andReturn(true);
            spyOn(http, 'createServer').andReturn(serverMock);
        });

        describe('instance.listen', function() {
            it('should create native server and listen on given host / port', function() {
                instance.listen(80, 'localhost', callback);
                expect(serverMock.listen).toHaveBeenCalledWith(80, 'localhost', callback);
            });

            it('should reattach listeners', function() {
                instance.listen(80, 'localhost', callback);
                expect(instance._reattachListeners).toHaveBeenCalled();
            });

            it('should set tcp backlog', function() {
                instance.listen(80, 'localhost', callback);
                expect(serverMock._backlog).toBe(4096);
            });
        });

        describe('instance.listenFD', function() {
            it('should create native server and listen on given FD', function() {
                instance.listenFD('fd', 'proto');
                expect(serverMock.listenFD).toHaveBeenCalledWith('fd', 'proto');
            });

            it('should reattach listeners', function() {
                instance.listenFD('fd', 'proto');
                expect(instance._reattachListeners).toHaveBeenCalled();
            });
        });

        describe('instance.close', function() {
            it('should close all native servers', function() {
                var server1 = jasmine.createSpyObj('server1', ['close']);
                var server2 = jasmine.createSpyObj('server2', ['close']);

                instance._nativeServers.push(server1);
                instance._nativeServers.push(server2);

                instance.close();

                expect(server1.close).toHaveBeenCalled();
                expect(server2.close).toHaveBeenCalled();
            });
        });

        describe('instance.getServerName', function() {
            it('should return node-server', function() {
                expect(instance.getServerName()).toEqual('node-server');
            });
        });
    });
});
