import * as WebSocket from 'ws';
import ClientBase from './clients/clientBase';
import MHSClient from './clients/sites/mhsClient';

var logger = require('./logger');

class ClientManager {
  clients: ClientBase[]|MHSClient[] = [];

  constructor() {
    //...maybe one day
  }

  addClient(data: any, ws: WebSocket) {
    if (data.client_type && !this.clientExists(data.user_id)) {
      var client = this.getClientType(data, ws);
      this.clients.push(client);
      logger.accessLog.info(`client added to client manager: ${data.user_id}`);
      return client;
    } else {
      logger.accessLog.info(`no client type designated or client already exists, socket disconnected: ${data.user_id}`);
      ws.close();
      return null;
    }
  }

  clientsOfType(client_type: string) {
    var result: ClientBase[]|MHSClient[] = [];

    for (let client of this.clients) {
      if (client.type() == client_type) {
        result.push(client);
      }
    }

    return result;
  }

  clientExists(id: number) {
    for (let client of this.clients) {
      if (client.id == id) {
        return client;
      }
    }

    return null;
  }

  getClient(id: number) {
    return this.clientExists(id);
  }

  removeClient(id: number) {
    var index: number = 0;

    for (let client of this.clients) {
      if (client.id == id) {
        client.ws.close();
        this.clients.splice(index, 1);
        logger.accessLog.info(`client disconnected: ${client.id}`);
        return true;
      }

      index++;
    }
  }

  getClientType(data: any, ws: WebSocket) {
    try {
      var Client = require(`./clients/${data.client_type}s/${data.client}client`);
      logger.accessLog.info(`attempting to create client of type ${data.client}, client id: ${data.user_id}...`);
      return new Client(data, ws);
    } catch (e) {
      logger.errorLog.info(e);
      logger.accessLog.info(`creating base client: ${data.user_id}`);
      return new ClientBase(data, ws);
    }
  }
};

export default ClientManager;


// { :client => 'mhs', :client_type => 'site', :user_id => 125, :user_type => 'user' }
// var exampleSocket = new WebSocket("wss://ysbraid.localhost:8443?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjp7ImNsaWVudCI6Im1ocyIsImNsaWVudF90eXBlIjoic2l0ZSIsInVzZXJfdHlwZSI6InVzZXIiLCJ1c2VyX2lkIjoxMjV9LCJleHAiOjE1NTI4MDExMDUsImF1ZCI6ImludGVybmFsIiwiaXNzIjoiWWFyZHN0aWNrIFNvZnR3YXJlIiwic3ViIjoiQnJhaWQgSldUIn0.fkfoqoWNjOeKfsXXJxh-9lBudhFsxhUt9fUIT1BXOLU");
