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

void cmd_whois(struct client* c, struct token* p, int n) {
  char nick[MAX_NICK];
  struct client* who;

  if(!n) {
    client_reply_start(c, "431");
    client_puts(c, ":No nickname given\r\n");
    return;
  }

  str_copyn(nick, MAX_NICK, p[0].s, p[0].len);

  who = client_find_by_nick(nick);
  if(!who) {
    client_reply_start(c, "406");
    client_puts(c, nick);
    client_puts(c, " :No such NICK\r\n");
    return;
  }

  client_reply_start(c, "311");
  client_puts(c, nick);
  client_puts(c, " unknown unknown * :Unknown\r\n");

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

  client_reply_start(c, "319");
  client_puts(c, nick);
  client_puts(c, " :");
  {
    int i;
    for(i = 0; i < MAX_USER_CHANNELS; i++) {
      if(who->channels[i].active) {
        if(i)
          client_puts(c, " ");
        client_puts(c, who->channels[i].s);
      }
    }
  }
  client_puts(c, "\r\n");

  client_reply_start(c, "317");
  client_puts(c, nick);
  client_puts(c, " ");
  {
    struct tai idle;
    char buf[FMT_ULONG];
    int buflen;

    tai_now(&idle);
    tai_sub(&idle, &idle, &who->stamp);

    buflen = fmt_ulong(buf, (unsigned long)tai_approx(&idle));
    client_put(c, buf, buflen);
  }
  client_puts(c, " :seconds idle\r\n");

  client_reply_start(c, "318");
  client_puts(c, nick);
  client_puts(c, " :End of WHOIS\r\n");
}
