 {CompositeDisposable} = require 'atom'
 {Emitter} = require 'event-kit'
 Crypto = require 'crypto'
+os = require 'os'
 Firebase = require 'firebase'
 Firepad = require './firepad-lib'
 

  getShareIdentifier: ->
    @shareIdentifier

  remove: ->
    # @firepad.dispose() # Won't work #4
    # @subscriptions.dispose()
    # @emitter.emit 'did-destroy'
    atom.notifications.addWarning('The "unshare" function is due dependencies buggy, and wont work. Please close the pane, to stop sharing!')

  onDidDestroy: (callback) ->

    @handleEditorEvents()

    hash = Crypto.createHash('sha256').update(@shareIdentifier).digest('base64')
    @userId = Math.random().toString(36).slice(2, 10)

    @firebase = new Firebase(atom.config.get('firepad.firebaseUrl')).child(hash)
    @firebaseUsers = @firebase.child('users')
    @firebaseContent = @firebase.child('content')

    @firebaseUsers.on 'value', (snapshot) =>
      @attachDecoration(snapshot)

    @firebaseUserSelf = @firebaseUsers.push
      userId: @userId
      displayName: os.hostname()
      pos: @editor.getCursorBufferPosition()
      color: '#' + Math.floor(Math.random() * 256 * 256 * 256).toString(16)

    @firebaseCursor = @firebaseUserSelf.child('pos')

    @firebaseContent.once 'value', (snapshot) =>
      options =
        sv_: Firebase.ServerValue.TIMESTAMP
        userId: @userId
      if not snapshot.val() and @editor.getText() isnt ''
        options.overwrite = true
      else
        @editor.setText ''
      @firepad = Firepad.fromAtom @firebaseContent, @editor, options

    #   @shareview.show(@shareIdentifier)

  handleEditorEvents: ->
    @subscriptions.add @editor.onDidChangeCursorPosition (event) =>
      @updateCursorPosition(event)

    @subscriptions.add @editor.onDidDestroy =>
      @remove()

