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

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

    Client& client = msg.getClient();

    std::string const& reason = (msg.getArgs().size() > 1) ? msg.getArgs()[1] : "";

    string_vector const& channels = split(msg.getArgs()[0], ",", true);
    for (size_t i = 0; i < channels.size(); ++i) {
        std::vector<Channel>::iterator it;
        it = std::find(_channels.begin(), _channels.end(), channels[i]);
        if (it == _channels.end()) {
            if (client.sendCode(ERR_NOSUCHCHANNEL, channels[i], "No such channel")) {
                return 1;
            }
            continue;
        }
        if (!it->isOnChannel(client)) {
            if (client.sendCode(ERR_NOTONCHANNEL, channels[i], "You're not on that channel")) {
                return 1;
            }
            continue;
        }
        it->partClient(client, reason);
        if (it->isChannelEmpty()) {
            _channels.erase(it);
            std::list<Client>::iterator itC;
            for (itC = _clients.begin(); itC != _clients.end(); ++itC) {
                itC->isInvited(*it);
            }
        }
    }
    return 0;
}
