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

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

    Client& client = msg.getClient();
    string_vector const& args = msg.getArgs();

    std::vector<Channel>::iterator itChannel;
    itChannel = std::find(_channels.begin(), _channels.end(), args[0]);
    if (itChannel == _channels.end()) {
        return client.sendCode(ERR_NOSUCHCHANNEL, args[0], "No such channel");
    }
    if (!itChannel->isOnChannel(client)) {
        return client.sendCode(ERR_NOTONCHANNEL, args[0],
                "You're not on that channel");
    }
    if (args.size() < 2) {
        return itChannel->sendTopic(client);
    } else {
        return itChannel->setTopic(client, args[1]);
    }
}
