#include "Protocol.h"
#include <sstream>

namespace Protocol {

std::string buildMessage(const std::string& command, 
                        const std::vector<std::string>& params) {
    std::ostringstream oss;
    oss << command;
    
    for (const auto& param : params) {
        oss << "|" << param;
    }
    
    oss << "\n";
    return oss.str();
}

bool parseMessage(const std::string& message, 
                 std::string& command, 
                 std::vector<std::string>& params) {
    if (message.empty()) {
        return false;
    }
    
    params.clear();
    std::istringstream iss(message);
    std::string token;
    
    // 获取命令
    if (!std::getline(iss, command, '|')) {
        return false;
    }
    
    // 移除可能的换行符
    if (!command.empty() && command.back() == '\n') {
        command.pop_back();
    }
    
    // 获取参数
    while (std::getline(iss, token, '|')) {
        // 移除可能的换行符
        if (!token.empty() && token.back() == '\n') {
            token.pop_back();
        }
        if (!token.empty()) {
            params.push_back(token);
        }
    }
    
    return true;
}

std::string buildResponse(bool success, const std::string& message) {
    std::vector<std::string> params;
    params.push_back(success ? "OK" : "ERROR");
    params.push_back(message);
    return buildMessage(S2C_RESPONSE, params);
}

std::string buildLoginOk(const std::string& username, 
                       const std::string& className,
                       int level, int hp, int mp) {
    std::vector<std::string> params;
    params.push_back(username);
    params.push_back(className);
    params.push_back(std::to_string(level));
    params.push_back(std::to_string(hp));
    params.push_back(std::to_string(mp));
    return buildMessage(S2C_LOGIN_OK, params);
}

std::string buildChatMessage(const std::string& sender, 
                            const std::string& message) {
    std::vector<std::string> params;
    params.push_back(sender);
    params.push_back(message);
    return buildMessage(S2C_MSG, params);
}

std::string buildPlayerList(const std::vector<std::string>& players) {
    std::ostringstream oss;
    for (size_t i = 0; i < players.size(); ++i) {
        if (i > 0) oss << ",";
        oss << players[i];
    }
    
    std::vector<std::string> params;
    params.push_back(oss.str());
    return buildMessage(S2C_LIST_PLAYERS, params);
}

std::string buildInvite(const std::string& inviter) {
    std::vector<std::string> params;
    params.push_back(inviter);
    return buildMessage(S2C_INVITE, params);
}

std::string buildBattleLog(const std::string& logMessage) {
    std::vector<std::string> params;
    params.push_back(logMessage);
    return buildMessage(S2C_BATTLE_LOG, params);
}

std::string buildSystemMessage(const std::string& message) {
    std::vector<std::string> params;
    params.push_back(message);
    return buildMessage(S2C_SYSTEM, params);
}

} // namespace Protocol
