import ClientBase from '../clients/clientBase';
import MHSClient from '../clients/sites/mhsClient';

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

class ChannelBase {
  id: string;
  clients: MHSClient[]|ClientBase[] = [];

  constructor(id: string) {
    this.id = id;
    logger.accessLog.info('Channel Created', {channelId: id});
  }

  addClient(client: MHSClient|ClientBase) {
    if (this.clientExists(client.id)) {
      logger.errorLog.info('Client already exits in channel', {channelId: this.id, clientId: client.id});
      return {'status': 'notice', 'message': 'client aleady exists in channel'};
    } else {
      this.clients.push(client);
      logger.accessLog.info('Added client to channel', {channelId: this.id, clientId: client.id});
      return {'status': 'success', 'message': 'client added'};
    }
  }

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

    return null;
  }

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

    for (let client of this.clients) {
      if (client.id == id) {
        this.clients.splice(index, 1);
        return true;
      }

      index++;
    }

    return false;
  }

  broadcastMessage(from: ClientBase|MHSClient|null, message: string) {
    for (let client of this.clients) {
      if (client != from) {
        client.ws.send(message);
        logger.accessLog.info(`sent to ${client.id}: `, {message: message});
      } else {
        logger.accessLog.info(`client is same as sender: ${client.id} - `, {message: message});
      }
    }

    return {'status': 'success', 'message': `message broadcast complete`};
  }
};

export default ChannelBase;
