mkry = require 'mockery';

Log = require '../../src/util/log'
Log.logtoConsole=false;

# OBJECT IN TEST
SiteBackend = null;

# MOCKS
validSite = 
  config: backend: "somehost"

downloadResponseMock = mock '';
httpMock = mock [ 'get', 'request' ];

resourceMock = mock 'fromServerResponse';

responseMock = mock [ 'writeHeader' ]

enableMockery = ()->
  mkry.enable warnOnUnregistered: false, warnOnReplace: false

  mkry.registerMock 'http', httpMock
  mkry.registerMock '../../models/resource', resourceMock

  SiteBackend = require '../../src/lib/backend'

disableMockery = ()->
  mkry.deregisterAll();
  mkry.disable();

checkSiteAndBackend = ()->

  tryExec = ->
    theBackend = new SiteBackend
  tryExec.should.throw()

  tryExec = ->
    theBackend = new SiteBackend {}
  tryExec.should.throw()

  tryExec = ->
    theBackend = new SiteBackend validSite
  tryExec.should.not.throw()

getFullResourceUrl = ()->
  theBackend = new SiteBackend validSite
  tests = 
    # input             #outpur
    '/'                 : 'http://somehost/'
    ''                  : 'http://somehost/'
    '/a'                : 'http://somehost/a'
    'a'                 : 'http://somehost/a'
    'a?b=c'             : 'http://somehost/a?b=c'
    'somehost/a'        : 'http://somehost/somehost/a'
    'http://somehost/a' : 'http://somehost/a'

  for path, expected of tests
    theBackend.fullURL(path).should.eql(expected);
  
downloadResource = (done)->
  httpMock.modify 'get', 
    takes: [ 'http://somehost/somepath', -> ]
    calls: 1
    with: [ "response" ]

  resourceMock.modify 'fromServerResponse',
    takes: [ "response" ]
    calls: 1,
    with: [ "resource" ]


  theBackend = new SiteBackend validSite
  theBackend.download '/somepath', (resource)-> 
    httpMock.isCalled('get').should.be.ok
    resourceMock.isCalled('fromServerResponse').should.be.ok
    resource.should.eql('resource')
    done();

pipeRequest = ()->
  # TODO: Improve this test.
  httpMock.modify 'request', 
    takes: (args)->
      opts = args[0];
      opts.headers.some_header.should.eql('some_h_val');
      opts.method.should.eql('post');
      opts.host.should.eql('somehost');

  theBackend = new SiteBackend validSite;
  theBackend.pipe {
    method: 'post',
    headers:
      some_header: 'some_h_val'
    url: '/something'
    pause: ->
    resume: ->
    pipe: ->
  }, responseMock

  # Though this is asynchronous, the mocks do it synchronously.
  # We can test the module synchronously. :)
  httpMock.isCalled('request').should.be.ok

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

  it 'should check for site and backend url', checkSiteAndBackend
  it 'should get full url for a resource', getFullResourceUrl
  it 'should download a resource', downloadResource
  it 'should pipe a request to bakend', pipeRequest