 async = require 'async'
 Viz = require '../dependencies/viz/viz.js'
 plantumlAPI = require './puml'
+codeChunkAPI = require './code-chunk'
 {svgAsPngUri} = require '../dependencies/save-svg-as-png/save-svg-as-png.js'
 
 getFileExtension = (documentType)->


                saveSvgAsPng svgElement, dest, {}, (error)->
                  document.body.removeChild(div)
                  cb(null, {dest, start, end, content})
            else
              cb(null, null)


              width = svgElement.getBBox().width
              height = svgElement.getBBox().height

              saveSvgAsPng svgElement, dest, {width, height}, (error)->
                cb(null, {dest, start, end, content, type: 'graph'})

        asyncFunc = helper(start, end, content)
        asyncFunctions.push asyncFunc
    else # code chunk
         # TODO: support this in the future
      helper = (start, end, content)->
        (cb)->
          def = lines[start].trim().slice(3)
          match = def.match(/^\{\s*(\"[^\"]*\"|[^\s]*|[^}]*)(.*)}$/)

          cmd = match[1].trim()
          cmd = cmd.slice(1, cmd.length-1).trim() if cmd[0] == '"'
          dataArgs = match[2].trim()

          options = null
          try
            options = JSON.parse '{'+dataArgs.replace((/([(\w)|(\-)]+)(:)/g), "\"$1\"$2").replace((/'/g), "\"")+'}'
          catch error
            atom.notifications.addError('Invalid options', detail: dataArgs)
            return

          codeChunkAPI.run content, rootDirectoryPath, cmd, options, (error, data, options)->
            outputType = options.output || 'text'

            if outputType == 'text'
              cb(null, {start, end, content, type: 'code_chunk', hide: options.hide, data, cmd})
            else if outputType == 'none'
              cb(null, {start, end, content, type: 'code_chunk', hide: options.hide, cmd})
            else if outputType == 'html'
              div = document.createElement('div')
              div.innerHTML = data
              if div.children[0].tagName.toLowerCase() == 'svg'
                dest = path.resolve(rootDirectoryPath, (Math.random().toString(36).substr(2, 9)) + '_cc.png')

                svgElement = div.children[0]
                width = svgElement.getBBox().width
                height = svgElement.getBBox().height
                saveSvgAsPng svgElement, dest, {width, height}, (error)->
                  cb(null, {start, end, content, type: 'code_chunk', hide: options.hide, dest, cmd})
              else
                cb(null, {start, end, content, type: 'code_chunk', hide: options.hide, data, cmd})
            else
              cb(null, null)

      asyncFunc = helper(start, end, content)
      asyncFunctions.push asyncFunc

  async.parallel asyncFunctions, (error, dataArray)->
    # TODO: deal with error in the future.
    #
    imagePaths = []

    for d in dataArray
      continue if !d
      {start, end, type} = d
      if type == 'graph'
        {dest} = d
        imgMd = "![](#{path.relative(rootDirectoryPath, dest)})"
        imagePaths.push dest

        lines[start] = imgMd

        i = start + 1
        while i <= end
          lines[i] = null # filter out later.
          i += 1
      else # code chunk
        {hide, data, dest, cmd} = d
        if hide
          i = start
          while i <= end
            lines[i] = null
            i += 1
          lines[end] = ''
        else # replace ```{python} to ```python
          line = lines[start]
          i = line.indexOf('```')
          lines[start] = line.slice(0, i+3) + cmd

        if dest
          imagePaths.push dest
          imgMd = "![](#{path.relative(rootDirectoryPath, dest)})"
          lines[end] += ('\n' + imgMd)

        if data
          lines[end] += ('\n' + data)

    lines = lines.filter (line)-> line!=null
              .join('\n')
