import { Environment, Router } from 'iotlogic-core';
import { WebSocketServerConnector } from 'locksmith-connector-ws';

export default class MessageServer {
  constructor(server) {
    this.connector = new WebSocketServerConnector({
      server,
      verifyClient: (info, cb) => {
        console.log(info);
        cb(true);
      }
    });
    this.router = new Router(this.connector, true);
    this.router.on('error', err => {
      console.log((err && err.stack) || err);
    });
    this.router.on('connect', () => {
      console.log('Connected!');
    });
    this.router.on('disconnect', () => {
      console.log('Disconnected!');
    });
    this.router.on('freeze', () => {
      console.log('Synchronizer frozen');
    });
    this.router.on('unfreeze', () => {
      console.log('Synchronizer unfrozen');
    });

    // Hard coded router for testing
    let environment = new Environment('server', this.router, {
      dynamic: true,
      dynamicPushWait: 10,
      dynamicTickWait: 10,
      fixedTick: 50,
      fixedBuffer: 0,
      disconnectWait: 10000,
      freezeWait: 1000
    });

    this.router.addSynchronizer('main', environment.synchronizer);
    
    this.connector.start();
  }
}

@@ -114,16 +114,48 @@
 r-ws';%0A%0A
+import %7B Device %7D from './db';%0A%0A
 export d
@@ -321,110 +321,867 @@
     
-console.log(info);%0A        cb(true);%0A      %7D%0A    %7D);%0A    this.router = new Router(this.connector, true
+let token = info.req.url.slice(1);%0A        // TODO server -%3E client push notification (with websocket)%0A        Device.findOne(%7B where: %7B token %7D %7D)%0A        .then(device =%3E %7B%0A          if (device == null) %7B%0A            cb(false, 401, 'Unauthorized');%0A            return;%0A          %7D%0A          info.req.device = device;%0A          cb(true);%0A        %7D, error =%3E %7B%0A          console.log(error);%0A          cb(false, 500, 'Internal server error');%0A        %7D);%0A      %7D%0A    %7D);%0A    this.router = new Router(this.connector, true, (_, clientId) =%3E %7B%0A      // Ignore data from the client; We've already loaded device info%0A      let data = this.connector.clients%5BclientId%5D.upgradeReq.device.toJSON();%0A      console.log(data);%0A      // :P%0A      for (let key in this.router.synchronizers) %7B%0A        this.router.synchronizers%5Bkey%5D.handleConnect(data, clientId);%0A      %7D%0A    %7D
 );%0A 
@@ -1959,20 +1959,16 @@
 nizer);%0A
-    
 %0A    thi

Implement socket connect handling with DB