/**
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.*
 */

const e2p = require('event-to-promise');
const Settings = require('../models/settings');
const WebSocket = require('ws');

class ThingConnection {
  constructor(href, messageHandler) {
    this.href = href;
    this.messageHandler = messageHandler;
    this.onMessage = this.onMessage.bind(this);
    this.ws = null;
  }

  async start() {
    const jwt = await Settings.get('RulesEngine.jwt');
    const gateway = await Settings.get('RulesEngine.gateway');
    const wsHref = gateway.replace(/^http/, 'ws') + this.href + '?jwt=' + jwt;

    this.ws = new WebSocket(wsHref);
    this.ws.on('message', this.onMessage);
    await e2p(this.ws, 'open');

    // Allow the app to handle the websocket open
    await new Promise(res => {
      setTimeout(res, 100);
    });
  }

  async send(msg) {
    await new Promise((resolve) => {
      this.ws.send(msg, function() {
        resolve();
      });
    });
  }

  stop() {
    if (this.ws) {
      this.ws.removeListener('message', this.onMessage);
      if (this.ws.readyState === WebSocket.OPEN) {
        this.ws.close();
      }
    } else {
      console.warn(this.constructor.name + '.stop was not started');
    }
  }


  onMessage(text) {
    let msg = JSON.parse(text);
    this.messageHandler(msg);
  }
}

module.exports = ThingConnection;

@@ -332,31 +332,226 @@
 );%0A%0A
-class ThingConnection %7B
+/**%0A * Manages WebSocket connection to a Thing%0A */%0Aclass ThingConnection %7B%0A  /**%0A   * @param %7BString%7CURL%7D href - Link to Thing endpoint%0A   * @param %7BFunction%3CObject%3E%7D messageHandler - called with messages from WS%0A   */
 %0A  c
@@ -718,24 +718,97 @@
  null;%0A  %7D%0A%0A
+  /**%0A   * Connect to the Thing's websocket%0A   * @return %7BPromise%7D%0A   */%0A
   async star
@@ -1246,16 +1246,127 @@
 );%0A  %7D%0A%0A
+  /**%0A   * Send a string over the websocket to the Thing%0A   * @param %7BString%7D msg%0A   * @return %7BPromise%7D%0A   */%0A
   async 
@@ -1493,16 +1493,58 @@
 );%0A  %7D%0A%0A
+  /**%0A   * Disconnect the websocket%0A   */%0A
   stop()
@@ -1799,17 +1799,16 @@
  %7D%0A  %7D%0A%0A
-%0A
   onMess

Document ThingConnection