webpage = require "webpage"
system = require "system"
fs = require "fs"

fetchUrl = (url, cb) ->
  responseStatus = false
  page = webpage.create()

  page.open url, (status) ->
    responseStatus = true if status == 'success'
    return

  page.onCallback = (data) ->
    if data != 'pageDone'
      return
    cb true, page.content, "pageDone"
    phantom.exit()
    return

  setTimeout () ->
    if responseStatus
      cb true, page.content, "timeout"
    else
      cb false, null
    phantom.exit()
  , 3000
  return

url = system.args[2]
path = system.args[1]

fetchUrl url, (status, content, log = null) ->
  fs.write path, JSON.stringify
    status: status
    content: content
    log: log
  , 'w'

