#include <iostream>
#include <libwebsockets.h>
#include <json/json.h>
#include <string>
#include <sstream>
#include <cstdlib>
#include <ctime>

// 信号类型定义
const std::string SIGNAL_TYPE_JOIN = "join";
const std::string SIGNAL_TYPE_RESP_JOIN = "resp-join";
const std::string SIGNAL_TYPE_LEAVE = "leave";
const std::string SIGNAL_TYPE_NEW_PEER = "new-peer";
const std::string SIGNAL_TYPE_PEER_LEAVE = "peer-leave";
const std::string SIGNAL_TYPE_OFFER = "offer";
const std::string SIGNAL_TYPE_ANSWER = "answer";
const std::string SIGNAL_TYPE_CANDIDATE = "candidate";

// 全局变量
std::string localUserId;
std::string remoteUserId;
int roomId = 0;
lws_context* context;
lws* wsi;

// 生成随机本地用户 ID
std::string generateRandomUserId() {
    static const char alphanum[] =
        "0123456789"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz";
    std::string userId;
    srand((unsigned)time(NULL));
    for (int i = 0; i < 8; ++i) {
        userId += alphanum[rand() % (sizeof(alphanum) - 1)];
    }
    return userId;
}

// 处理 ICE 候选
void handleIceCandidate(const Json::Value& candidateMsg) {
    std::cout << "Candidate: " << candidateMsg.toStyledString() << std::endl;
}

// 获取分辨率（这里只是示例，实际可能需要更多处理）
void getResolutions() {
    std::cout << "获取分辨率逻辑待实现" << std::endl;
}

// 创建并发送 offer 消息
void createOfferAndSendMessage(const Json::Value& session) {
    Json::Value jsonMsg;
    jsonMsg["cmd"] = "offer";
    jsonMsg["roomId"] = roomId;
    jsonMsg["uid"] = localUserId;
    jsonMsg["remoteUid"] = remoteUserId;
    jsonMsg["msg"] = session.toStyledString();

    Json::FastWriter writer;
    std::string message = writer.write(jsonMsg);

    unsigned char buf[LWS_PRE + 1024];
    memcpy(&buf[LWS_PRE], message.c_str(), message.length());
    lws_write(wsi, &buf[LWS_PRE], message.length(), LWS_WRITE_TEXT);
}

// 处理创建 offer 错误
void handleCreateOfferError(const std::string& error) {
    std::cerr << "handleCreateOfferError: " << error << std::endl;
}

// 创建并发送 answer 消息
void createAnswerAndSendMessage(const Json::Value& session) {
    Json::Value jsonMsg;
    jsonMsg["cmd"] = "answer";
    jsonMsg["roomId"] = roomId;
    jsonMsg["uid"] = localUserId;
    jsonMsg["remoteUid"] = remoteUserId;
    jsonMsg["msg"] = session.toStyledString();

    Json::FastWriter writer;
    std::string message = writer.write(jsonMsg);

    unsigned char buf[LWS_PRE + 1024];
    memcpy(&buf[LWS_PRE], message.c_str(), message.length());
    lws_write(wsi, &buf[LWS_PRE], message.length(), LWS_WRITE_TEXT);
}

// 回调函数
static int callback(struct lws* wsi, enum lws_callback_reasons reason, void* user, void* in, size_t len) {
    switch (reason) {
    case LWS_CALLBACK_CLIENT_ESTABLISHED: {
        std::cout << "websocket open" << std::endl;
        // 加入房间
        Json::Value jsonMsg;
        jsonMsg["cmd"] = "join";
        jsonMsg["roomId"] = roomId;
        jsonMsg["uid"] = localUserId;

        Json::FastWriter writer;
        std::string message = writer.write(jsonMsg);

        unsigned char buf[LWS_PRE + 1024];
        memcpy(&buf[LWS_PRE], message.c_str(), message.length());
        lws_write(wsi, &buf[LWS_PRE], message.length(), LWS_WRITE_TEXT);
        std::cout << "doJoin message: " << message << std::endl;
        break;
    }
    case LWS_CALLBACK_CLIENT_RECEIVE: {
        std::string message(static_cast<char*>(in), len);
        Json::Reader reader;
        Json::Value jsonMsg;
        if (reader.parse(message, jsonMsg)) {
            std::string cmd = jsonMsg["cmd"].asString();
            if (cmd == SIGNAL_TYPE_NEW_PEER) {
                remoteUserId = jsonMsg["remoteUid"].asString();
                std::cout << "handleRemoteNewPeer, remoteUid: " << remoteUserId << std::endl;
                // 发送 offer
                Json::Value session;
                createOfferAndSendMessage(session);
            }
            else if (cmd == SIGNAL_TYPE_RESP_JOIN) {
                remoteUserId = jsonMsg["remoteUid"].asString();
                std::cout << "handleResponseJoin, remoteUid: " << remoteUserId << std::endl;
            }
            else if (cmd == SIGNAL_TYPE_PEER_LEAVE) {
                remoteUserId = jsonMsg["remoteUid"].asString();
                std::cout << "handleRemotePeerLeave, remoteUid: " << remoteUserId << std::endl;
            }
            else if (cmd == SIGNAL_TYPE_OFFER) {
                Json::Value desc;
                Json::Reader descReader;
                descReader.parse(jsonMsg["msg"].asString(), desc);
                std::cout << "handleRemoteOffer" << std::endl;
                // 发送 answer
                Json::Value answerSession;
                createAnswerAndSendMessage(answerSession);
            }
            else if (cmd == SIGNAL_TYPE_ANSWER) {
                Json::Value desc;
                Json::Reader descReader;
                descReader.parse(jsonMsg["msg"].asString(), desc);
                std::cout << "handleRemoteAnswer" << std::endl;
            }
            else if (cmd == SIGNAL_TYPE_CANDIDATE) {
                Json::Value candidateMsg;
                Json::Reader candidateReader;
                candidateReader.parse(jsonMsg["msg"].asString(), candidateMsg);
                handleIceCandidate(candidateMsg);
            }
        }
        else {
            std::cerr << "onMessage parse Json failed" << std::endl;
        }
        break;
    }
    case LWS_CALLBACK_CLIENT_CLOSED: {
        std::cout << "websocket closed" << std::endl;
        break;
    }
    default:
        break;
    }
    return 0;
}

// 定义协议数组
static struct lws_protocols protocols[] = {
    {
        "example-protocol",
        callback,
        0,
        0,
    },
    {NULL, NULL, 0, 0}
};

int main() {
    // 生成本地用户 ID
    localUserId = generateRandomUserId();

    struct lws_context_creation_info info;
    memset(&info, 0, sizeof(info));
    info.port = CONTEXT_PORT_NO_LISTEN;
    info.protocols = protocols;
    info.gid = -1;
    info.uid = -1;
    info.options = LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
    info.ssl_cert_filepath = NULL;
    info.ssl_private_key_filepath = NULL;

    context = lws_create_context(&info);
    if (context == NULL) {
        std::cerr << "Failed to create libwebsockets context" << std::endl;
        return -1;
    }

    struct lws_client_connect_info ccinfo = { 0 };
    ccinfo.context = context;
    ccinfo.address = "47.117.155.230";
    ccinfo.port = 10000;
    ccinfo.path = "/";
    ccinfo.host = ccinfo.address;
    ccinfo.origin = ccinfo.address;
    ccinfo.protocol = protocols[0].name;
    ccinfo.ssl_connection = LCCSCF_USE_SSL | LCCSCF_ALLOW_SELFSIGNED | LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK;

    wsi = lws_client_connect_via_info(&ccinfo);
    if (wsi == NULL) {
        std::cerr << "Failed to connect to server" << std::endl;
        lws_context_destroy(context);
        return -1;
    }

    while (1) {
        lws_service(context, 50);
    }

    lws_context_destroy(context);
    return 0;
}