import {expect} from 'chai'
import path     from 'path'

import Promise   from 'bluebird'
import Registry  from '../lib/services/Registry'
import Repo      from '../lib/services/Repo'
import Events    from '../lib/utils/Events'
import * as Time from '../lib/utils/Time'

import * as thinky from '../lib/thinky'

import record    from './fixtures/Repo'

describe("Registry ::", function () {

  let registry = null
  
  it("Registry.create()                    -> return <Promise>", done => {
    Registry.create().then( instance => {
      registry = instance
      expect(registry).to.be.instanceof(Registry)
      expect(registry).to.have.property('repos')
      done()
    }).catch(done) 
  })
  
  it("Registry.appDir                      -> return <String>", () => {
    expect(path.isAbsolute(Registry.appDir()), `was ${Registry.appDir()}`).to.equal(true)
  })

  it("Registry.ensureAppDir()    -> return <Promise>", done => {
    Registry.ensureAppDir().then( err => {
      expect(err).to.be.null
      done()
    }).catch(done) 
  })

  it("Registry.prototype.emit[evt]         -> returns <Self>", () => {
    
    Object.keys(Registry.Event).forEach( evt => {
      expect(Registry).to.respondTo( Events.methodName(evt) )
    })
  })

  it.skip("Registry.prototype.register()        -> return <Repo>", function (done) {
    this.timeout(Time.seconds(20))
    const registerer = registry.register(record).then( repo => {
      expect(repo).to.be.instanceof(Repo)
      expect(registry.repos).to.have.property(record.name)
      done()
    })
    expect(registerer).to.be.instanceof(Promise)
  })

  it.skip("Registry.prototype.deref()           -> return <Registry>", ()=> {
    registry.deref(record)
    expect(registry.repos).to.be.empty
  })

  it("Registry.prototype.add()             -> return <Registry>", function (done) {
    this.timeout(Time.seconds(20))

    registry.once( Registry.Event.update, repo => {
      expect(repo).to.be.instanceof(Repo)
      done()
    })

    registry.once( Registry.Event.error, err => {
      done(err)
    })

    registry.add(record).then( instance => {
      registry = instance
      expect(registry).to.be.instanceof(Registry)
    }).catch(done)
  })

  it("Registry.prototype.subscribe()       -> return <Promise>", () => {
    expect(Registry).to.respondTo('subscribe')
  })

  after( done => {
    
    registry.kill()
    
    Promise.all([
        Registry.drop()
      , registry.repo(record).rm()
    ]).then( _ => {
      registry = null
      thinky.kill()
      done() 
    }).catch(done)
  })

})
