var domify = require('domify')
var render = require('templayed')

module.exports = function Component (d) {
  var C = {
    id : d.key.split(':')[1] // set id to hash
  }

  var parent
  var pkg = d.value // examine d.value + d.key
  var template = pkg.html

  C.html = (!pkg.body)
    ? domify(template)
    : domify(render(template)(pkg.body))

  C.draw = function (arg, cb) { // allow template mod / render
    if (arg) {
      if (typeof arg === 'object' && !arg.tagName)
        C.html = domify(render(template)(arg))
      if (typeof arg === 'string')
        parent = document.querySelector(arg)
      if (typeof arg === 'object' && arg.tagName)
        parent = arg
    }
    if (!parent) parent = document.body
    parent.appendChild(C.html)
    C.live = true
    C.html.id = C.id
    if (C.bind) C.bind(C.html)
  }

  C.erase = function (cb) {
    parent.removeChild(C.html)
    C.live = false
    if (C.unbind) C.unbind()
  }

  C.live = false

  if (pkg.nimoy.module) C.s = require(pkg.name)(C)

  if (!C && pkg && pkg.nimoy.module) C = {s : require(pkg.name)()}

  return C
}

// if !args to draw fn use pkg defaults 

// streams should be optional

var domify = require('domify')
var render = require('templayed')

module.exports = function Component (d) {
  var C = {
    id : d.key.split(':')[1]
  }

  var parent
  var pkg = d.value
  var template = pkg.html

  C.html = (!pkg.body)
    ? domify(template)
    : domify(render(template)(pkg.body))

  C.draw = function (arg, cb) {
    if (arg) {
      if (typeof arg === 'object' && !arg.tagName)
        C.html = domify(render(template)(arg))
      if (typeof arg === 'string')
        parent = document.querySelector(arg)
      if (typeof arg === 'object' && arg.tagName)
        parent = arg
    }

    if (!parent) parent = document.body

    parent.appendChild(C.html)

    C.live = true
    C.html.id = C.id

    if (C.onDraw) C.onDraw(C.html)
  }

  C.erase = function (cb) {
    parent.removeChild(C.html)
    C.live = false
    if (C.onErase) C.onErase()
  }

  C.live = false

  if (pkg.nimoy.module) C.s = require(pkg.name)(C)
  if (!C && pkg && pkg.nimoy.module) C = {s : require(pkg.name)()}

  return C

}
// if !args to draw fn use pkg defaults 
// streams should be optional!

call onDraw/onErase after draw/erase