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

static void part(struct client* c, const char* name, const char* reason) {
  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, "442");
    client_puts(c, "PART :You're not on that channel\r\n");
    return;
  }

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

  client_del_channel(c, name);
}

void cmd_part(struct client* c, struct token* p, int n) {
  struct token channel;
  char reason[512];

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

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

  if(n > 1)
    str_copyn(reason, sizeof reason, p[1].s, p[1].len);
  else
    str_copyn(reason, sizeof reason, c->nick, -1);

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

    channel_commalist_parsenext(&channel, name);
    part(c, name, reason);
  }
}
