SiteMapUpdateStrategy = require '../../../src/lib/cache/update_strategy/sitemap'

cacheMock = mock [ 'keyFor', 'has', 'update' ]
backendMock = mock [ 'download' ]

siteMapContents = """
      <?xml version="1.0" encoding="UTF-8"?>
      <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
        <url>
          <loc>http://www.site.com/page-one</loc>
          <priority>1.0</priority>
        </url>
        <url>
          <loc>http://www.site.com/page-two</loc>
          <priority>1.0</priority>
        </url>
        <url>
          <loc>http://www.site.com/page-three</loc>
          <priority>1.0</priority>
        </url>
      </urlset>
"""

checkInputs = ()->
  tryExec = ->
    smStrategy = new SiteMapUpdateStrategy()
  tryExec.should.throw();

  tryExec = ->
    smStrategy = new SiteMapUpdateStrategy("cache")
  tryExec.should.throw();

  tryExec = ->
    smStrategy = new SiteMapUpdateStrategy("cache","backend")
  tryExec.should.not.throw();

readSiteMap = (done)->
  backendMock.modify 'download',
    takes: [ '/sitemap.xml', -> ]
    calls: 1
    with: [
      content: siteMapContents
    ]
  theUS = new SiteMapUpdateStrategy("cache", backendMock)

  theUS.readSitemap (pages)=>
    pages.length.should.eql(3);
    pages[0].should.eql('/page-one');
    pages[1].should.eql('/page-two');
    pages[2].should.eql('/page-three');
    done();

sitemap404 = (done)->
  backendMock.modify 'download',
    takes: [ '/sitemap.xml', -> ]
    calls: 1
    with: [ null ]

  theUS = new SiteMapUpdateStrategy("cache", backendMock)

  theUS.readSitemap (pages)=>
    pages.length.should.eql(0);
    done();

filterCache = ()->
  cacheMock.modify 'keyFor', returns: 'somekey'
  cacheMock.modify 'has', returns: true

  theUS = new SiteMapUpdateStrategy(cacheMock, backendMock)
  filtered = theUS.filterExisting ['/page-one','/page-two','/page-three'];
  filtered.length.should.eql(0)

  cacheMock.modify 'has', returns: false
  filtered = theUS.filterExisting ['/page-one','/page-two','/page-three'];
  filtered.length.should.eql(3)

updateCache = ()->
  theUS = new SiteMapUpdateStrategy(cacheMock, backendMock);
  theUS.updatePages(['/page-one','/page-two','/page-three'])

  cacheMock.modify 'update', (args)->
    args[0].match /^\/page-/ and args[1] is 'From sitemap'

  cacheMock.isCalled('update').should.be.ok
  cacheMock.getCallCount('update').should.eql(3)

describe 'Sitemap Cache Update strategy', ->
  it 'should check for backend and cache', checkInputs 
  it 'should read sitemap', readSiteMap 
  it 'should return empty array if sitemap is not found', sitemap404 
  it 'should filter pages in cache', filterCache 
  it 'should update cache for filterd pages', updateCache 
