import { create } from 'skypager-registry'
import mapValues from 'lodash/mapValues'

export function use (options = {}, next) {
  attach(this, options)
  next && next()
}

export function attach(project, defaults = {}) {
  project.registries = create({
    name: 'registries',
    type: 'Directory',
    silenceFailures: true
  })

  project.createRegistry = createRegistry.bind(project)

  mapValues(defaults, (options = {}, name) => {
    project.createRegistry(name, options)
  })

  return project
}

export function createRegistry (name, options = {}) {
  const project = this

  if (project.registries.available.indexOf(name) >= 0) {
    return project.registries.lookup(name)
  }

  project.registries.register(name, () => create({
    name,
    type: 'Directory',
    ...options,
  }))

  if (options.prop !== false && typeof project[name] === 'undefined') {
    project.hideGetter(name, () => project.registries.lookup(name))
  }
}
