-{Emitter} = require('atom')
+{CompositeDisposable,Emitter} = require('atom')
 
 # ------------------------------------------------------------------------------
 
 class Workspace
 
-  ## Construction and initialization -------------------------------------------
+  ## Construction --------------------------------------------------------------
 
   constructor: ->
     @emitter = new Emitter
     @levelCodeEditorsById = {}
     @activeLevelCodeEditor = null
+    @activeLevelCodeEditorSubscrs= new CompositeDisposable
 
   ## Event subscription --------------------------------------------------------
 

  onDidChangeActiveLevelCodeEditor: (callback) ->
    @emitter.on('did-change-active-level-code-editor',callback)

  ## Workspace properties ------------------------------------------------------

  isActive: ->

  isLevelCodeEditor: (textEditor) ->
    @getLevelCodeEditorForTextEditor(textEditor)?

  ## Managing the active level code editor -------------------------------------

  getActiveLevelCodeEditor: ->
    @activeLevelCodeEditor

  getActiveLanguage: ->
    @activeLevelCodeEditor.getLanguage()

  getActiveLevel: ->
    @activeLevelCodeEditor.getLevel()

  setActiveLevelCodeEditor: (levelCodeEditor) ->
    if @isActive()
      unless levelCodeEditor.getId() is @activeLevelCodeEditor.getId()
        newLanguage = levelCodeEditor.getLanguage()
        oldLanguage = @activeLevelCodeEditor.getLanguage()
        newLevel = levelCodeEditor.getLevel()
        oldLevel = @activeLevelCodeEditor.getLevel()
        @unsubscribeFromActiveLevelCodeEditor()
        @activeLevelCodeEditor = levelCodeEditor
        if newLanguage.getName() isnt oldLanguage.getName()
          @emitter.emit('did-change-active-level',newLevel)
          @emitter.emit('did-change-active-language',{newLanguage,newLevel})
        else if newLevel.getName() isnt oldLevel.getName()
          @emitter.emit('did-change-active-level',newLevel)
        @subscribeToActiveLevelCodeEditor()
        @emitter.emit('did-change-active-level-code-editor',@activeLevelCodeEditor)
    else
      @activeLevelCodeEditor = levelCodeEditor
      @subscribeToActiveLevelCodeEditor()
      @emitter.emit('did-enter-workspace',@activeLevelCodeEditor)

  unsetActiveLevelCodeEditor: ->
    if @isActive()
      @unsubscribeFromActiveLevelCodeEditor()
      @activeLevelCodeEditor = null
      @emitter.emit('did-exit-workspace')

  subscribeToActiveLevelCodeEditor: ->
    @activeLevelCodeEditorSubscrs.add \
      @activeLevelCodeEditor.onDidChangeLanguage (language,level) =>
        @emitter.emit('did-change-active-language',{language,level})
    @activeLevelCodeEditorSubscrs.add \
      @activeLevelCodeEditor.onDidChangeLevel (level) =>
        @emitter.emit('did-change-active-level',level)

  unsubscribeFromActiveLevelCodeEditor: ->
    @activeLevelCodeEditorSubscrs.dispose()

# ------------------------------------------------------------------------------

