 _ = require 'underscore'
 moment = require 'moment'
 Bacon = require 'bacon.model'
+Q = require 'q'
 
 clearExtent = (v) -> _.extend {}, v, {extent: null}
 setBrushing = (v) -> _.extend {}, v, {brushing: true}


    legend_target.exit().remove()

  {draw, destroy}

module.exports = {create}

  destroy = ->
    _.each(destroyFunctions, (f) -> f())
    destroyFunctions = []

  exportImage = ->
    deferred = Q.defer()
    canvas = document.createElement('canvas')
    rect = svg.node().getBoundingClientRect()
    canvas.width = rect.width
    canvas.height = rect.height
    ctx = canvas.getContext('2d')
    svgString = new XMLSerializer().serializeToString(svg.node())
    svgBlob = new Blob([svgString], {type: 'image/svg+xml;charset=utf-8'})
    url = URL.createObjectURL(svgBlob)
    img = new Image
    img.src = url
    img.onload = ->
      ctx.drawImage(img, 0, 0)
      dataUrl = canvas.toDataURL()
      deferred.resolve(dataUrl)
    img.onerror = (e) ->
      deferred.reject(e)
    deferred.promise.finally ->
      URL.revokeObjectURL(url)

  draw = (data, params) ->
    destroy()
