-path                  = require 'path'
 fs                    = require 'fs'
 {CompositeDisposable, Disposable} = require 'atom'
 {$, $$$, ScrollView}  = require 'atom-space-pen-views'
 _                     = require 'underscore-plus'
+path                  = require 'path'
+os                    = require 'os'
 
 module.exports =
 class AtomHtmlPreviewView extends ScrollView


    if @editorId?
      @resolveEditor(@editorId)
    else
      if atom.workspace?
        @subscribeToFilePath(filePath)

      @renderHTMLCode()

  save: ->
    # Temp file path
    outPath = path.resolve os.tmpdir() + @editor.getTitle()
    # Add base tag; allow relative links to work despite being loaded
    # as the src of an iframe
    out = "<base href=\"" + @getPath() + "\">" + @editor.getText()
    fs.writeFileSync outPath, out
    @tmpPath = outPath

  renderHTMLCode: (text) ->
    if not atom.config.get("atom-html-preview.triggerOnSave") and @editor.getPath()? then @save()
    iframe = document.createElement("iframe")
    # Fix from @kwaak (https://github.com/webBoxio/atom-html-preview/issues/1/#issuecomment-49639162)
    # Allows for the use of relative resources (scripts, styles)
    iframe.setAttribute("sandbox", "allow-scripts allow-same-origin")
    iframe.src = @tmpPath
    @html $ iframe
    # @trigger('atom-html-preview:html-changed')
    atom.commands.dispatch 'atom-html-preview', 'html-changed'
