 TextMateGrammar = require 'text-mate-grammar'
 Package = require 'package'
-fs = require 'fs-utils'
+fsUtils = require 'fs-utils'
 _ = require 'underscore'
 $ = require 'jquery'
 CSON = require 'cson'

  requireMainModule: ->
    return @mainModule if @mainModule
    mainModulePath = @getMainModulePath()
    @mainModule = require(mainModulePath) if fs.isFile(mainModulePath)

  getMainModulePath: ->
    return @mainModulePath if @resolvedMainModulePath
    @resolvedMainModulePath = true
    mainModulePath =
      if @metadata.main
        fs.join(@path, @metadata.main)
      else
        fs.join(@path, 'index')
    @mainModulePath = fs.resolveExtension(mainModulePath, ["", _.keys(require.extensions)...])

  registerDeferredDeserializers: ->
    for deserializerName in @metadata.deferredDeserializers ? []

      console.warn "Failed to activate package named '#{@name}'", e.stack

  loadMetadata: ->
    if metadataPath = fsUtils.resolveExtension(fsUtils.join(@path, 'package'), ['cson', 'json'])
      @metadata = CSON.readObject(metadataPath)
    @metadata ?= {}

  loadKeymaps: ->
    @keymaps = []

    keymapsDirPath = fsUtils.join(@path, 'keymaps')
    keymapExtensions = ['cson', 'json', '']

    if @metadata.keymaps
      for path in @metadata.keymaps
        @keymaps.push(CSON.readObject(fsUtils.resolve(keymapsDirPath, path, keymapExtensions)))
    else
      for path in fsUtils.list(keymapsDirPath, ['cson', 'json', '']) ? []
        @keymaps.push(CSON.readObject(path))

  loadStylesheets: ->
    @stylesheets = []
    stylesheetDirPath = fsUtils.join(@path, 'stylesheets')
    for stylesheetPath in fsUtils.list(stylesheetDirPath, ['css', 'less']) ? []
      @stylesheets.push([stylesheetPath, loadStylesheet(stylesheetPath)])

  loadGrammars: ->
    @grammars = []
    grammarsDirPath = fsUtils.join(@path, 'grammars')
    for grammarPath in fsUtils.list(grammarsDirPath, ['.cson', '.json']) ? []
      @grammars.push(TextMateGrammar.loadSync(grammarPath))

  loadScopedProperties: ->
    scopedPropertiessDirPath = fsUtils.join(@path, 'scoped-properties')
    for scopedPropertiesPath in fsUtils.list(scopedPropertiessDirPath, ['.cson', '.json']) ? []
      for selector, properties of fsUtils.readObject(scopedPropertiesPath)
        syntax.addProperties(selector, properties)

  serialize: ->
