mkry = require 'mockery';
require('../../src/util/log').logtoConsole = false;
siteCacheMock = mock ['has', 'get', 'keyFor', 'update'];
resMock = mock ['writeHead', 'end'];

siteCacheMock.modify 'keyFor', returns: "xxxx"
siteCacheMock.modify 'get', 
  returns: 
    cachedAt: (new Date()).toString();
    headers: 
      something: "header val", 
    content: "cached content", 
  takes: ['xxxx']
siteCacheMock.modify 'has', returns: true, takes: ['xxxx']

siteMock = 
  cache: siteCacheMock
  canCache: -> true; #always true

enableMockery = ()->
  mkry.enable warnOnUnregistered: false, warnOnReplace: false
  
disableMockery = ()->
  mkry.deregisterAll();
  mkry.disable();

cacheCheck = ()->
  CacheDispatcher = require('../../src/lib/dispatcher/cache_dispatcher')
  tryExec = ->
    theCDis = new CacheDispatcher {};
  tryExec.should.throw();
  tryExec = ->
    theCDis = new CacheDispatcher cache: "dummyCache"
  tryExec.should.not.throw();

serveReq = ()->
  CacheDispatcher = require('../../src/lib/dispatcher/cache_dispatcher')

  theCDis = new CacheDispatcher siteMock;

  resMock.modify 'writeHead', takes: (args)->
    args[0].should.eql "200"
    args[1].should.have.property('something')
    args[1].something.should.eql('header val')
    return true;

  resMock.modify 'end', takes: ["cached content"]

  theCDis.dispatch {
    url: "/something",
    method: "get"
  }, resMock, ->

  resMock.isCalled('writeHead').should.be.ok
  resMock.isCalled('end').should.be.ok
  siteCacheMock.isCalled('keyFor').should.be.ok
  siteCacheMock.isCalled('get').should.be.ok

additionalHeader = ()->
  CacheDispatcher = require('../../src/lib/dispatcher/cache_dispatcher')
  
  resMock.modify 'writeHead', takes: (args)->
    args[1].should.have.property('via')
    args[1].via.should.eql('X-noDelay')
    args[1].should.have.property('cached-time')
    return true;

  theCDis = new CacheDispatcher(siteMock);

  theCDis.dispatch {
    url: "/something",
    method: "get"
  }, resMock, ->
  
  resMock.isCalled("writeHead").should.be.ok

resourceNotFound = ()->
  siteCacheMock.modify 'has', returns: false;

  CacheDispatcher = require('../../src/lib/dispatcher/cache_dispatcher')
  
  theCDis = new CacheDispatcher(siteMock);

  proxyDispatcherMock = mock('dispatch')

  theCDis.dispatch {
    url: "/something",
    method: "get"
  }, resMock, -> proxyDispatcherMock.dispatch();

  proxyDispatcherMock.isCalled('dispatch').should.be.ok

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

  it 'should check for site and cache', cacheCheck
  it 'should serve GET request if resource present in cache', serveReq
  it 'should set via, cachedTime headers when serving request', additionalHeader
  it 'should call next function if not found in cache', resourceNotFound