mkry = require 'mockery'

connectMock = mock ['connect']
connectAppMock = mock ['use']
cacheDispathcerMock = mockClass ['dispatch']
proxyDispathcerMock = mockClass ['dispatch']

connectMock.modify 'connect', returns: connectAppMock

enableMockery = ()->
  mkry.enable warnOnUnregistered: false, warnOnReplace: false
  # Context mismatch, so using it inside function. :(
  mkry.registerMock 'connect', -> connectMock.connect() 
  mkry.registerMock './cache_dispatcher', cacheDispathcerMock.constructorFn
  mkry.registerMock './proxy_dispatcher', proxyDispathcerMock.constructorFn
  
disableMockery = ()->
  mkry.deregisterAll();
  mkry.disable();
  connectMock.reset();
  connectAppMock.reset();
  cacheDispathcerMock.reset();
  proxyDispathcerMock.reset();

noSite = ()->
  SiteDispatcher = require '../../src/lib/dispatcher'
  tryExec = ->
    theDispactcher = new SiteDispatcher

  tryExec.should.throw();


  tryExec = ->
    theDispactcher = new SiteDispatcher {}

  tryExec.should.not.throw();

initDispatchers = ()->
  cacheDispathcerMock.modify 'constructor',
    takes: [ 'site' ]

  proxyDispathcerMock.modify 'constructor',
    takes: [ 'site' ]

  SiteDispatcher = require '../../src/lib/dispatcher'
  theDispactcher = new SiteDispatcher 'site'

  theDispactcher.init();
  cacheDispathcerMock.isInstantiated().should.be.ok
  proxyDispathcerMock.isInstantiated().should.be.ok

dispatcherApp = ()->
  SiteDispatcher = require '../../src/lib/dispatcher'
  theDispactcher = new SiteDispatcher 'site'

  theDispactcher.cacheDispatcher = dispatch: -> 'dispatcher'
  theDispactcher.proxyDispatcher = dispatch: -> 'dispatcher'

  theDispactcher.app().should.eql(connectAppMock)
  connectMock.isCalled('connect').should.be.ok
  connectAppMock.isCalled('use').should.be.ok


describe 'Site Dispatcher', ->
  beforeEach enableMockery
  afterEach disableMockery

  it 'should check for cache and backend', noSite
  it 'should initialize cache dispatcher and proxy dispatcher', initDispatchers  
  it 'should create a app to dispatch the site', dispatcherApp