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

int
Server::_cmdPRIVMSG(Message const& msg)
{
    string_vector const& args = msg.getArgs();
    Client& client = msg.getClient();

    if (args.empty()) {
        return client.sendCode(ERR_NORECIPIENT, ":No recipient given (PRIVMSG)");
    }
    if (args.size() < 2) {
        return client.sendCode(ERR_NOTEXTTOSEND, ":No text to send");
    }
    string_vector const& recipients = split(args[0], ",", true);
    for (size_t i = 0; i < recipients.size(); ++i) {
        std::list<Client>::iterator itClient;
        for (itClient = _clients.begin(); itClient != _clients.end(); ++itClient) {
            if (itClient->nick == recipients[i]) {
                itClient->sendMsg(client.nick, "PRIVMSG " + itClient->nick, args[1]);
                continue;
            }
        }
        for (size_t j = 0; j < _channels.size(); ++j) {
            if (_channels[j].getName() == recipients[i]) {
                _channels[j].sendMessage(args[1], &client);
                continue;
            }
        }
    }
    return 0;
}
