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

static void names(struct client* c, const char* name) {
  struct member_list channel;
  int i;

  client_reply_start(c, "353");
  client_puts(c, "= ");
  client_puts(c, name);
  client_puts(c, " :");

  channel_members(name, &channel);

  for(i = 0; i < channel.n; i++) {
    if(i)
      client_puts(c, " ");
    client_puts(c, channel.v[i]->nick);
  }
  client_puts(c, "\r\n");
}

void cmd_names(struct client* c, struct token* p, int n) {
  if(!n) {
    struct channel_list channels;
    int i;

    channel_list_all(&channels);
    for(i = 0; i < channels.n; i++)
      names(c, channels.v[i]);

    client_reply_start(c, "366");
    client_puts(c, "*");
    client_puts(c, " :End of /NAMES\r\n");
  }

  else {
    struct token clist;
    clist = p[0];
    while(clist.len > 0) {
      char name[MAX_CHANNEL + 1];

      channel_commalist_parsenext(&clist, name);
      names(c, name);
      client_reply_start(c, "366");
      client_puts(c, name);
      client_puts(c, " :End of /NAMES\r\n");
    }
  }
}
