#include "case.h"
#include "byte.h"
#include "str.h"

#include "channel.h"
#include "client.h"
#include "command.h"

void channel_members(const char* name, struct member_list* m) {
  int i, j;

  m->n = 0;

  for(i = 0; i < MAX_CLIENTS; i++) {
    if(!clients[i].active)
      continue;
    for(j = 0; j < MAX_USER_CHANNELS; j++) {
      /* !! should be channel_equals ? */
      if(clients[i].channels[j].active &&
          str_equal(clients[i].channels[j].s, name)) {
        m->v[m->n++] = &clients[i];
        break;
      }
    }
  }
}

void channel_message_start(struct member_list* m, struct client *f, 
    const char* s) {
  int i;

  for(i = 0; i < m->n; i++)
    client_message_start(m->v[i], f, s);
}

void channel_puts(struct member_list* m, const char* s) {
  channel_put(m, s, str_len(s));
}

void channel_put(struct member_list* m, const char* s, unsigned int len) {
  int i;

  for(i = 0; i < m->n; i++)
    client_put(m->v[i], s, len);
}

void channel_commalist_parsenext(struct token* list, char* name) {
  unsigned int len;

  len = byte_chr(list->s, list->len, ',');
  str_copyn(name, MAX_CHANNEL, list->s, len);
  if(len == list->len) {
    list->s += len;
    list->len = 0;
  }
  else {
    list->s += len+1;
    list->len -= len+1;
  }
}

static void channel_list_add(struct channel_list* c, const char* channel) {
  int i;

  for(i = 0; i < c->n; i++)
    if(case_equals(c->v[i], channel))
      return;

  c->v[c->n++] = channel;
}

void channel_list_all(struct channel_list* c) {
  int i, j;

  c->n = 0;

  for(i = 0; i < MAX_CLIENTS; i++)
    if(clients[i].active)
      for(j = 0; j < MAX_USER_CHANNELS; j++)
        if(clients[i].channels[j].active)
          channel_list_add(c, clients[i].channels[j].s);
}


