#include "Message.hpp"
#include "Client.hpp"
#include "log.hpp"
#include "split.hpp"
#include "errcodes.hpp"
#include <iostream>

Message::Message(Client& client, const std::string& raw) : _client(client), _raw(raw), _cmd(), _args()
{
    if (_raw == "") {
        return;
    }

    string_vector major_split = split(_raw, " :");

    while (major_split.size() > 2) {
        size_t size = major_split.size();
        major_split[size - 2] += " :" + major_split[size - 1];
        major_split.pop_back();
    }

    _args = split(major_split[0], " ", true);
    if (major_split.size() == 2) {
        _args.push_back(major_split[1]);
    }

    if (!_args.empty()) {
        _cmd = _args[0];
        _args.erase(_args.begin());
    }
}

const std::string&
Message::getRaw() const
{
    return _raw;
}

const std::string&
Message::getCmd() const
{
    return _cmd;
}

int
Message::expectArgs(unsigned int count) const
{
    if (getArgs().size() < count) {
        LOG << _cmd << " expects " << count << " parameters" << std::endl;
        if (_client.sendCode(ERR_NEEDMOREPARAMS, _cmd, "Not enough parameters")) {
            return -1;
        }
        return 1;
    }
    return 0;
}

const string_vector&
Message::getArgs() const
{
    return _args;
}

Client&
Message::getClient() const
{
    return _client;
}

std::ostream&
operator<<(std::ostream &os, const Message& msg)
{
    os << "CMD: '" << msg.getCmd() << '\'' << std::endl;
    os << "ARGS: ";
    string_vector const& args = msg.getArgs();
    for (size_t i = 0; i < args.size(); ++i) {
        os << '\'' << args[i] << "'\t";
    }
    return os;
}
