#include "Server.hpp"
#include "errcodes.hpp"
#include <algorithm>

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

    Client& client = msg.getClient();

    std::list<Client>::iterator guest = std::find(_clients.begin(),
                                                  _clients.end(),
                                                  msg.getArgs()[0]);
    std::vector<Channel>::iterator channel = std::find(_channels.begin(),
                                                       _channels.end(),
                                                       msg.getArgs()[1]);
    if (guest == _clients.end()) {
        return client.sendCode(ERR_NOSUCHNICK, msg.getArgs()[0], "No such nick");
    }
    if (channel == _channels.end()) {
        goto send_invite_msg;
    }
    if (!channel->isOnChannel(client)) {
        return client.sendCode(ERR_NOTONCHANNEL, msg.getArgs()[1],
                               "You're not on that channel");
    }
    if (channel->isOnChannel(*guest)) {
        return client.sendCode(ERR_USERONCHANNEL,
                               msg.getArgs()[0] + ' ' + msg.getArgs()[1],
                               "is already on channel");
    }
    if (channel->isInviteOnly() && !channel->isOp(client)) {
        return client.sendCode(ERR_CHANOPRIVSNEEDED, msg.getArgs()[1],
                               "You're not channel operator");
    }

    guest->addInvite(*channel);
send_invite_msg:
    guest->sendMsg(client.nick,
                   "INVITE " + msg.getArgs()[0] + ' ' + msg.getArgs()[1],
                   "");
    return client.sendCode(RPL_INVITING,
                           msg.getArgs()[1] + ' ' + msg.getArgs()[0],
                           "");
}
