 path = require 'path'
 
 _ = require 'underscore-plus'
+async = require 'async'
 CSON = require 'season'
 fs = require 'fs-plus'
 {Emitter} = require 'emissary'

  loadGrammars: ->
    @grammars = []

    loadGrammar = (grammarPath) =>
      atom.syntax.readGrammar grammarPath, (error, grammar) =>
        if error?
          console.warn("Failed to load grammar: #{grammarPath}", error.stack ? error)
        else
          @grammars.push(grammar)
          grammar.activate() if @grammarsActivated

    grammarsDirPath = path.join(@path, 'grammars')
    fs.list grammarsDirPath, ['.json', '.cson'], (error, grammarPaths=[]) ->
      loadGrammar(grammarPath) for grammarPath in grammarPaths

  loadScopedProperties: ->
    @scopedProperties = []

    loadScopedPropertiesFile = (scopedPropertiesPath) =>
      ScopedProperties.load scopedPropertiesPath, (error, scopedProperties) =>
        if error?
          console.warn("Failed to load scoped properties: #{scopedPropertiesPath}", error.stack ? error)
        else
          @scopedProperties.push(scopedProperties)
          scopedProperties.activate() if @scopedPropertiesActivated

    scopedPropertiesDirPath = path.join(@path, 'scoped-properties')
    fs.list scopedPropertiesDirPath, ['.json', '.cson'], (error, scopedPropertiesPaths=[]) ->
      for scopedPropertiesPath in scopedPropertiesPaths
        loadScopedPropertiesFile(scopedPropertiesPath)

  serialize: ->
    if @mainActivated

        @loadKeymaps()
        @loadMenus()
        @loadStylesheets()
        @grammarsPromise = @loadGrammars()
        @scopedPropertiesPromise = @loadScopedProperties()
        @requireMainModule() unless @metadata.activationEvents?

      catch e
