 window.retro = retro = document.createElement 'canvas', 'x-game'
 document.body.appendChild retro
 
-cores =
-  'snes9x-next': require 'snes9x-next'
-  'vba-next': require 'vba-next'
-  'nestopia': require 'nestopia'
-  'gambatte': require 'gambatte'
-
-readFile = (file) ->
-  new Promise (resolve, reject) ->
-    reader = new FileReader()
-    reader.readAsArrayBuffer file
-    reader.onload = (event) ->
-      resolve new Uint8Array reader.result
-    reader.onerror = reject
-
-readFileEntry = (entry) ->
-  new Promise (resolve, reject) ->
-    entry.file resolve, reject
-  .then (file) ->
-    readFile file
-
-getSave = (filename) ->
-  new Promise (resolve, reject) ->
-    chrome.syncFileSystem.requestFileSystem (fs) ->
-      fs.root.getFile filename, create: true, resolve, reject
-    , reject
+onkey = (event) ->
+  if retro.player and settings.keys.hasOwnProperty event.which
+    pressed = event.type == 'keydown'
+    retro.player.inputs[0].buttons[settings.keys[event.which]] ?= {}
+    retro.player.inputs[0].buttons[settings.keys[event.which]].pressed = pressed
+    event.preventDefault()
 
 autosaver = 0
 

sparkmd5 = require 'sparkmd5'
JSZip = require 'jszip'
require 'x-game'
localForage = require 'localforage'

settings = require './settings.json!'
utils = require './utils'

  window.removeEventListener 'keydown', onkey
  window.clearInterval autosaver

play = (rom, extension) ->
  Promise.resolve()
  .then ->
    throw 'no rom!' if not rom
    retro.md5 = sparkmd5.ArrayBuffer.hash rom
    Promise.all([
      System.import settings.extensions[extension]
      localForage.getItem retro.md5
    ]).then ([core, save]) ->
      stop() if retro.running
      retro.core = core
      core.load_game rom if rom
      core.unserialize new Uint8Array save if save?
      core.set_input_poll ->
        gamepads = navigator.getGamepads() if navigator.getGamepads
        retro.player.inputs = gamepads if gamepads and gamepads[0]
      retro.player.inputs = [
        buttons: {}
      ]
      autosaver = setInterval ->
        localForage.setItem retro.md5, new Uint8Array core.serialize()
      , 1000
      window.addEventListener 'keydown', onkey
      window.addEventListener 'keyup', onkey
      retro.start()

loadData = (filename, buffer) ->
  draghint.classList.add 'hidden'
  extension = utils.getExtension filename
  rom = null
  if extension is 'zip'
    zip = new JSZip buffer
    for file in zip.file /.*/ # any way to predict name of file?
