+sparkmd5 = require 'sparkmd5'
+JSZip = require 'jszip'
+require 'x-game'
+
+settings = require './settings.json!'
+
 draghint = document.getElementById 'draghint'
 chooser = document.getElementById 'chooser'
 


navigator.serviceWorker.register 'worker.js' if navigator.serviceWorker

md5 = require('sparkmd5').ArrayBuffer.hash
JSZip = require 'jszip'

require 'x-game'
retro = document.createElement 'canvas', 'x-game'
document.body.appendChild retro

cores =
  gb: 'gambatte'
  gbc: 'gambatte'
  smc: 'snes9x-next'
  fig: 'snes9x-next'
  sfc: 'snes9x-next'
  swc: 'snes9x-next'
  gba: 'vba-next'
  nes: 'nestopia'

keys =
  9: 8
  13: 9
  16: 8
  18: 1
  32: 0
  37: 14
  38: 12
  39: 15
  40: 13
  65: 1
  66: 0
  68: 15
  73: 3
  74: 2
  75: 0
  76: 1
  82: 5
  83: 13
  87: 12
  88: 3
  89: 2
  90: 3
  91: 2
  222: 8

play = (rom, extension) ->
  retro.md5 = md5 rom
  Promise.all([
    System.import cores[extension]
  ]).then ([core, save]) ->
    retro.core = core
    retro.game = rom if rom

    zip = new JSZip buffer
    for file in zip.file /.*/ # any way to predict name of file?
      [..., extension] = file.name.split '.'
      if settings.cores[extension]
        rom = new Uint8Array file.asArrayBuffer()
        break
  else if settings.cores[extension]
    rom = buffer
  if rom
    stop() if retro.running
