noflo = require 'noflo'
chai = require 'chai' unless chai
path = require 'path'
baseDir = path.resolve __dirname, '../'

describe 'GetItem component', ->
  c = null
  repository = null
  token = null
  path = null
  out = null
  error = null
  beforeEach (done) ->
    @timeout 10000
    loader = new noflo.ComponentLoader baseDir
    loader.load 'harpy/GetItem', (err, instance) ->
      c = instance
      c.once 'ready', ->
        repository = noflo.internalSocket.createSocket()
        token = noflo.internalSocket.createSocket()
        path = noflo.internalSocket.createSocket()
        out = noflo.internalSocket.createSocket()
        error = noflo.internalSocket.createSocket()
        c.inPorts.repository.attach repository
        c.inPorts.token.attach token
        c.inPorts.path.attach path
        c.outPorts.out.attach out
        c.outPorts.error.attach error
        done()

  describe 'fetching a Front Matter document', ->
    it 'should produce a standard Poly item', (done) ->
      groups = []
      received = false
      error.on 'data', (data) ->
        done data
      out.on 'begingroup', (group) ->
        groups.push group
      out.on 'data', (data) ->
        chai.expect(data).to.be.an 'object'
        chai.expect(data.id).to.be.a 'string'
        chai.expect(data.html).to.be.a 'string'
        chai.expect(data.html.indexOf('</h1>')).not.to.equal -1
        chai.expect(data.metadata).to.be.an 'object'
        chai.expect(data.id).to.equal '_posts/2015-11-22-sailing-across-the-atlantic.md'
        chai.expect(data.metadata['@type']).to.equal 'Article'
        chai.expect(groups).to.eql [
          'foo'
          '_posts/2015-11-22-sailing-across-the-atlantic.md'
        ]
        received = true
      out.on 'endgroup', ->
        groups.pop()
      out.on 'disconnect', ->
        chai.expect(groups.length).to.equal 0
        chai.expect(received).to.equal true
        done()

      repository.beginGroup 'foo'
      repository.send 'the-domains/bergie-today'
      repository.endGroup()
      repository.disconnect()
      token.beginGroup 'foo'
      token.send process.env.GITHUB_API_TOKEN
      token.endGroup()
      token.disconnect()
      path.beginGroup 'foo'
      path.send '_posts/2015-11-22-sailing-across-the-atlantic.md'
      path.endGroup()
      path.disconnect()
