   Config
 ) ->
   class CommandStore
-    commands: null
+    commands: []
+    lastSync: null
     fileEntry: null
+
     constructor: ->
       _.extend this, Backbone.Events
       @requestFileSystem(

      @fs.root.getFile "commands.json", { create: true }, ((fileEntry) =>
        @fileEntry = fileEntry
        fileEntry.file @readFile.bind(this), @onLoadError.bind(this)
      ), console.log.bind(console, "error loading file")

    sync: ->
      return _.defer @trigger.bind(this, "synced") if @commands

      $.getJSON "#{Config.API_URL}/commands", (response) =>
        @commands = response
        @trigger "synced"
        @storeCommands()

    requestFileSystem: (
      window.requestFileSystem ||

      reader.readAsText file
      self = this
      reader.onloadend = ->
        self.parseFile @result
        self.trigger "initialised"

    parseFile: (content) ->
      return unless content

      try
        json = JSON.parse content
      catch e
        console.log "Error parsing file"
        return

      @commands = json.commands
      @lastSync = json.lastSync

    storeCommands: ->
      @fileEntry.createWriter ((fileWriter) =>
        json = JSON.stringify {
          commands: @commands
          lastSync: @lastSync
        }
        blob = new Blob [json], type: "application/json"

        fileWriter.write blob
        fileWriter.onwriteend = \
          console.log.bind console, "Successfully wrote file"
        fileWriter.onerror = console.log.bind console, "Error writing file"
      ), console.log.bind(console, "Error creating writer")

