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

int
Server::_cmdQUIT(Message const& msg)
{
    Client& client = msg.getClient();
    std::string quit;
    if (msg.getArgs().empty()) {
        quit = client.username;
    } else {
        quit = msg.getArgs()[0];
    }
    std::list<Client>::iterator it;
    for (it = _clients.begin(); it != _clients.end(); ++it) {
        for (size_t i = 0; i < _channels.size(); ++i) {
            if (_channels[i].areOnChannel(client, *it)) {
                it->sendMsg(client.nick, "QUIT", quit);
                goto next_client;
            }
        }
next_client:;
    }
    for (size_t i = 0; i < _channels.size(); ++i) {
        _channels[i].removeClient(client);
        if (_channels[i].isChannelEmpty()) {
            _channels.erase(_channels.begin() + i);

            std::list<Client>::iterator itC;
            for (itC = _clients.begin(); itC != _clients.end(); ++itC) {
                itC->isInvited(_channels[i]);
            }
        }
    }
    removeClient(client);
    return 1;
}
