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

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

  if(name[0] != '#') {
    client_reply_start(c, "403");
    client_puts(c, name);
    client_puts(c, " :No such channel\r\n");
    return;
  }

  if(client_is_member(c, name)) {
    client_reply_start(c, "405");
    client_puts(c, name);
    client_puts(c, " :You are already a member\r\n");
    return;
  }

  if(client_add_channel(c, name) < 0) {
    client_reply_start(c, "405");
    client_puts(c, name);
    client_puts(c, " :You have joined too many channels\r\n");
    return;
  }

  channel_members(name, &channel);
  channel_message_start(&channel, c, "JOIN");
  channel_puts(&channel, ":");
  channel_puts(&channel, name);
  channel_puts(&channel, "\r\n");

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

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

void cmd_join(struct client* c, struct token* p, int n) {
  struct token clist;

  if(!n) {
    client_reply_start(c, "461");
    client_puts(c, "JOIN :Not enough parameters\r\n");
    return;
  }

  if(!c->nick[0]) {
    client_reply_notregistered(c);
    return;
  }

  if(p[0].len == 1 && p[0].s[0] == '0') {
    int i;

    for(i = 0; i < MAX_USER_CHANNELS; i++) {
      if(c->channels[i].active) {
        struct member_list channel;
        channel_members(c->channels[i].s, &channel);
        channel_message_start(&channel, c, "PART");
        channel_puts(&channel, c->channels[i].s);
        channel_puts(&channel, "\r\n");

        c->channels[i].active = 0;
      }
    }

    return;
  }

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

    channel_commalist_parsenext(&clist, name);
    join(c, name);
  }
}
