ScheduledUpdateStrategy = require '../../../src/lib/cache/update_strategy/scheduled'
Log = require '../../../src/util/log'
Log.logtoConsole = false;

moment = require 'moment'

siteCacheMock = mock ['getAll','update'];
backendMock = {}; # not really needed

alreadyTimedOut = (done)->
  siteCacheMock.modify 'getAll',
    returns:[
      {lastUpdated: moment().subtract('days', 1), path: 'somepath1', contentType: -> 'text/html'}
      {lastUpdated: moment().subtract('days', 2), path: 'somepath2', contentType: -> 'text/css'}
      {lastUpdated: moment().subtract('days', 3), path: 'somepath3', contentType: -> 'text/js'}
    ]

  theUS = new ScheduledUpdateStrategy(siteCacheMock, backendMock);

  theUS.setSchedules [
    {
      "name": "HTML Pages",
      "refresh_interval": "2 hours",
      "content_type": "text/html",
      "path": "*"
    }
  ]

  siteCacheMock.modify 'update', 
    takes: [ 'somepath1', 'Scheduled update(Overdue)', -> ]
    calls: 2

  theUS.init ->
    siteCacheMock.isCalled('update').should.be.ok
    siteCacheMock.getCallCount('update').should.eql(1)
    done();

setupTimers = (done)->
  siteCacheMock.modify 'getAll',
    returns:[
      {lastUpdated: moment().subtract('minutes', 1), path: 'somepath1', contentType: -> 'text/html'}
      {lastUpdated: moment().subtract('minutes', 2), path: 'somepath2', contentType: -> 'text/css'}
      {lastUpdated: moment().subtract('minutes', 3), path: 'somepath3', contentType: -> 'text/js'}
    ]

  theUS = new ScheduledUpdateStrategy(siteCacheMock, backendMock);

  theUS.setSchedules [
    {
      "name": "HTML Pages",
      "refresh_interval": "2 hours",
      "content_type": "text/html",
      "path": "*"
    }
  ]

  siteCacheMock.modify 'update', 
    takes: [ 'somepath1', 'Scheduled update(Overdue)', -> ]
    calls: 2

  theUS.init ->
    theUS.scheduleObjs[0].timers.length.should.eql(1)
    done();

describe 'Scheduled update strategy', ->
  it 'should call update on already timed out resources', alreadyTimedOut
  it 'should setup timers to all matching resources which are not timed out', setupTimers