#include "Server.hpp"
#include "errcodes.hpp"

int
Server::_cmdNICK(Message const& msg)
{
    if (int rv = msg.expectArgs(1)) {
        return rv == -1 ? rv : 0;
    }

    Client& client = msg.getClient();
    static std::string const special("[]\\`_^{|}");

    std::string const& nick = msg.getArgs()[0];

    std::list<Client>::iterator it = _clients.begin();
    for (; it != _clients.end(); ++it) {
        if (client == *it) {
            continue;
        }
        if (nick == it->nick) {
            return client.sendCode(ERR_NICKNAMEINUSE, nick, "Nickname is already in use");
        }
    }
    if (nick.length() > 9 || nick.length() < 1 ||
        (!std::isalpha(nick[0]) && special.find(nick[0]) == special.npos))
    {
        return client.sendCode(ERR_ERRONEUSNICKNAME, nick, "Erroneous nickname");
    }
    for (size_t i = 1; i < nick.length(); ++i) {
        if (!std::isdigit(nick[i]) && !std::isalpha(nick[i]) &&
           special.find(nick[i]) == special.npos && nick[i] != '-')
        {
            return client.sendCode(ERR_ERRONEUSNICKNAME, nick, "Erroneous nickname");
        }
    }
    client.nick = nick;
    if (client.getRegistered() && !client.getWelcomed()) {
        return _welcomeClient(client);
    }
    return 0;
}
