import createRouter from 'router';
import debug from 'debug';
import fs from 'fs';

// routes
import authenticate from './routes/authenticate';
import playlist from './routes/playlists';
import waitlist from './routes/waitlist';
import search from './routes/search';
import booth from './routes/booth';
import users from './routes/users';
import staff from './routes/staff';
import chat from './routes/chat';
import now from './routes/now';

// middleware
import authenticator from './middleware/authenticator';
import WSServer from './sockets';

const log = debug('uwave:api:v1');

/**
 * creates a router for version 1 of the api
 *
 * @param {Object} options - router config, for more information see {@link http://expressjs.com/4x/api.html#router}
 **/
export default class V1 {
  constructor(config = {}) {
    this.router = createRouter(config.router);
    this.cert = '';
    this.wsserver = null;

    this.setCert(config.cert);

    this.router.use(authenticator(this));

    authenticate(this, this.router);
    playlist(this.router);
    waitlist(this.router);
    search(this.router);
    booth(this.router);
    users(this.router);
    staff(this.router);
    chat(this.router);
    now(this.router);
  }

  getRouter() {
    return this.router;
  }

  setCert(filepath) {
    fs.readFile(filepath, 'UTF8', (err, content) => {
      if (err) return log(`couldn't load cert. Error: ${err}`);
      this.cert = content;
    });
  }

  getCert() {
    return this.cert;
  }

  registerWSServer(uwave) {
    if (!this.wsserver) {
      this.wsserver = new WSServer(this, uwave, uwave.getConfig());
    } else {
      this.log('wsserver is already registered');
    }
  }

  destroy() {
    this.wsserver.destroy();
    this.wsserver = null;
    this.router = null;
  }
}

@@ -790,16 +790,20 @@
 tructor(
+uw, 
 config =
@@ -805,24 +805,288 @@
 fig = %7B%7D) %7B%0A
+    if (!uw %7C%7C !('mongo' in uw)) %7B%0A      throw new Error(%60%0A        Expected a u-wave-core instance in the first parameter. If you are%0A        developing, you may have to upgrade your u-wave-* modules.%0A      %60.replace(/%5Cs+/g, ' ').trim());%0A    %7D%0A%0A    this.uw = uw;%0A
     this.rou
@@ -1149,31 +1149,56 @@
    this.
-wsserver = null
+sockets = new WSServer(this, uw, config)
 ;%0A%0A    t
@@ -1777,62 +1777,20 @@
 %0A%0A  
-registerWSServer(uwave) %7B%0A    if (!this.wsserver
+destroy(
 ) %7B%0A
-  
     
@@ -1798,141 +1798,16 @@
 his.
-wsserver = new WSServer(this, uwave, uwave.getConfig());%0A    %7D else %7B%0A      this.log('wsserver is already registered');%0A    %7D%0A  %7D%0A%0A  
+sockets.
 dest
@@ -1803,34 +1803,33 @@
 ockets.destroy()
- %7B
+;
 %0A    this.wsserv
@@ -1826,45 +1826,15 @@
 his.
-wsserver.destroy();%0A    this.wsserver
+sockets
  = n

create socket server immediately, remove "registerWSServer"