 _ = require 'underscore-plus'
 fs = require 'fs-plus'
 async = require 'async'
+Q = require 'q'
 
 ### Internal ###
 


  legalGrammarExtensions: ['plist', 'tmLanguage', 'tmlanguage', 'json', 'cson']

  loadGrammars: (done) ->
    fs.isDirectory @getSyntaxesPath(), (isDirectory) =>
      if isDirectory
        fs.list @getSyntaxesPath(), @legalGrammarExtensions, (error, paths) =>
          if error?
            console.log("Error loading grammars of TextMate package '#{@path}':", error.stack, error)
            done()
          else
            async.eachSeries(paths, @loadGrammarAtPath, done)
      else
        done()

  loadGrammarAtPath: (grammarPath, done) =>
    atom.syntax.readGrammar grammarPath, (error, grammar) =>
      if error?
        console.log("Error loading grammar at path '#{grammarPath}':", error.stack ? error)
      else
        @addGrammar(grammar)
        done?()

  loadGrammarsSync: ->
    for grammarPath in fs.listSync(@getSyntaxesPath(), @legalGrammarExtensions)
      @addGrammar(atom.syntax.readGrammarSync(grammarPath))

  addGrammar: (grammar) ->
    @grammars.push(grammar)

    @measure 'loadTime', =>
      @metadata = Package.loadMetadata(@path, true)

  activate: ({sync, immediate}={})->
    if sync or immediate
      @loadGrammarsSync()
      @loadScopedPropertiesSync()
    else
      TextMatePackage.addPackageToActivationQueue(this)

  activateConfig: -> # noop

