var browserify = require("browserify")
var fs = require("fs")
var path = require("path")
var cuid = require("cuid")

var fileName = process.argv[2]
var src = fs.readFileSync(path.resolve(fileName), "utf8")

function addLink(href) {
    return "" +
        "var link = document.createElement('link')\n" +
        "link.rel = 'stylesheet'\n" +
        "link.href = '" + href + "'\n" +
        "document.head.appendChild(link)\n"
}

var code = "" +
    "var createEditor = require('javascript-editor')\n" +
    "var elem = document.createElement('div')\n" +
    addLink("https://rawgithub.com/maxogden/" +
        "javascript-editor/master/css/codemirror.css") +
    addLink("https://rawgithub.com/maxogden/" +
        "javascript-editor/master/css/theme.css") +
    "document.body.appendChild(elem)\n" +
    "setTimeout(function () {\n" +
    "    var editor = createEditor({\n" +
    "        container: elem,\n" +
    "        value: " + JSON.stringify(src) + ",\n" +
    "        readOnly: true\n" +
    "    })\n" +
    "}, 100)"
var loc = path.join(__dirname, cuid() + ".js")
fs.writeFileSync(loc, code)

var bundle = browserify()
bundle.add(path.resolve(fileName))
bundle.add(loc)
var stream = bundle.bundle()
stream.pipe(process.stdout)
stream.on("end", function () {
    fs.unlinkSync(loc)
})

@@ -493,24 +493,274 @@
 itor')%5Cn%22 +%0A
+    %22window.addEventListener('load', function () %7B%5Cn%22 +%0A    %22    var editor = createEditor(%7B%5Cn%22 +%0A    %22        container: elem,%5Cn%22 +%0A    %22        value: %22 + JSON.stringify(src) + %22,%5Cn%22 +%0A    %22        readOnly: true%5Cn%22 +%0A    %22    %7D)%5Cn%22 +%0A    %22%7D)%5Cn%22 +%0A
     %22var ele
@@ -794,24 +794,66 @@
 'div')%5Cn%22 +%0A
+    %22document.body.appendChild(elem)%5Cn%22 +%0A
     addLink(
@@ -1046,282 +1046,8 @@
 ss%22)
- +%0A    %22document.body.appendChild(elem)%5Cn%22 +%0A    %22setTimeout(function () %7B%5Cn%22 +%0A    %22    var editor = createEditor(%7B%5Cn%22 +%0A    %22        container: elem,%5Cn%22 +%0A    %22        value: %22 + JSON.stringify(src) + %22,%5Cn%22 +%0A    %22        readOnly: true%5Cn%22 +%0A    %22    %7D)%5Cn%22 +%0A    %22%7D, 100)%22
 %0Avar

create editor on load