 
 primaryDisplay = null
 windows = null
+counter = 0
+
+cacheDirPromise = Promise.promise (resolve, reject) ->
+  dirName = path.resolve __dirname, '../cache'
+  mkdirp dirName, (err) ->
+    return reject err if err
+    resolve dirName
+
+getCacheImagePath = (url, width, height) ->
+  cacheDirPromise
+  .then (cacheDir) ->
+    hash = crypto
+      .createHash 'md5'
+      .update String(width) + String(height) + url
+      .digest 'hex'
+    path.join cacheDir, "#{hash}.png"
 
 closeWindows = ->
   return unless windows?.length > 0

path = require 'path'

electron = require 'electron'

Launcher = require './launcher'


      height: bounds.height
      enableLargerThanScreen: true
      frame: false
    window._id = counter++
    window.setBounds bounds, false

    setTimeout ->
      win = _.find windows, (w) -> w == window
      return unless win?
      getCacheImagePath display.url, bounds.width, bounds.height
      .then (fileName) ->
        Promise.promise (resolve, reject) ->
          fs.exists fileName, (exists) ->
            if exists
              resolve false
            else
              resolve fileName
      .then (fileName) ->
        return unless fileName
        Promise.promise (resolve, reject) ->
          window.capturePage (img) ->
            png = img?.toPng?()
            resolve png
        .then (imgBuffer) ->
          return unless imgBuffer
          fs.writeFile fileName, imgBuffer, (err) ->
            return console.log err if err
    , 5000

    window.loadURL display.url

    window.on 'closed', ->
      closeWindows()
      console.log 'windows closed, show launcher', arguments
      Launcher.show primaryDisplay

    windows.push window

ipcMain.on 'launch', (event, data) ->
  createWindows data.displays

app.on 'ready', ->
  electronScreen = electron.screen
  primaryDisplay = electronScreen.getPrimaryDisplay()
  Launcher.show primaryDisplay
