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

#define TARGET_LEN ((MAX_CHANNEL) > (MAX_NICK) ? (MAX_CHANNEL) : (MAX_NICK))

void cmd_privmsg(struct client* c, struct token* p, int n) {
  char target[TARGET_LEN];

  if(n < 1) {
    client_reply_start(c, "411");
    client_puts(c, ":No recipient given (PRIVMSG)\r\n");
    return;
  }
  if(n < 2) {
    client_reply_start(c, "412");
    client_puts(c, ":No text to send\r\n");
    return;
  }

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

  str_copyn(target, TARGET_LEN, p[0].s, p[0].len);

  if(target[0] == '#') {
    struct member_list channel;

    if(!client_is_member(c, target)) {
      client_reply_start(c, "404");
      client_puts(c, ":Cannot send to channel you're not a member of.\r\n");
      return;
    }
    
    channel_members(target, &channel); 
    client_remove_from_list(c, &channel);
    channel_message_start(&channel, c, "PRIVMSG");
    channel_puts(&channel, target);
    channel_puts(&channel, " :");
    channel_put(&channel, p[1].s, p[1].len);
    channel_puts(&channel, "\r\n");
  }

  else {
    struct client* to = client_find_by_nick(target);
    if(!to) {
      client_reply_start(c, "401");
      client_puts(c, target);
      client_puts(c, " :No such nick\r\n");
      return;
    }

    if(to->is_away) {
      client_reply_start(c, "301");
      client_puts(c, " ");
      client_puts(c, to->nick);
      client_puts(c, " :");
      client_puts(c, to->away_reason);
      client_puts(c, "\r\n");
    }

    client_puts(to, ":");
    client_puts(to, c->nick);
    client_puts(to, " PRIVMSG ");
    client_puts(to, target);
    client_puts(to, " :");
    client_put(to, p[1].s, p[1].len);
    client_puts(to, "\r\n");
  }

}
