'use babel'

import AtomSocket from 'atom-socket'
import { EventEmitter } from 'events'
import { Socket } from 'phoenix'

export default class Terminal {
  constructor(args={}) {
    this.emitter = new EventEmitter();

    this.host = args.host;
    this.port = args.port;
    this.path = args.path;
    this.token = args.token;
    this.username = args.username;

    this.hasFailed = false;

    this.connect();
  }

  connect() {
    this.socket = new Socket(this.url(), {params: {token: this.token}})
    this.socket.connect()

    this.channel = this.socket.channel(`session:${this.username}`)

    this.channel.join()
      .receive('error', reject)
      .receive('ok', (e) => {
        this.emit('open', e)
        resolve(this.channel)
      })

    this.channel.on('terminal_output', ({terminal_output}) => {
      var decoded = new Buffer(terminal_output, 'base64').toString()
      this.emit('message', decoded)
    })

    this.channel.on('close', e => this.emit('close', e))
    this.channel.on('error', e => this.emit('error', e))
  }

  emit() {
    return this.emitter.emit.apply(this.emitter, arguments);
  }

  on() {
    return this.emitter.on.apply(this.emitter, arguments);
  }

  url() {
    var {version} = require('../package.json');
    var protocol = (this.port === 443) ? 'wss' : 'ws';

    return `${protocol}://${this.host}:${this.port}/${this.path}`;
  }

  reset() {
    return this.socket.reset();
  }

  send(msg) {
    var encoded = new Buffer(msg).toString('base64')
    this.channel.push('terminal_input', {data: encoded})
  }
}

@@ -645,14 +645,64 @@
 r', 
-reject
+(e) =%3E %7B console.log(%22error connecting to session%22, e) %7D
 )%0A  
@@ -762,38 +762,8 @@
  e)%0A
-        resolve(this.channel)%0A
     
@@ -964,26 +964,22 @@
 annel.on
-('c
+C
 lose
-', 
+(
 e =%3E thi
@@ -1017,26 +1017,22 @@
 annel.on
-('e
+E
 rror
-', 
+(
 e =%3E thi

update close and error handlers for phoenix