#include "l_socket.h"

static SQInteger SquirrelSendMsg(HSQUIRRELVM v)
{
    const SQChar *Str;
    sq_getstring(v, 2, &Str);

    l_socket::getInstance().Send(Str);
    return 0;
}

void l_socket::InitSqr()
{
    std::lock_guard<std::recursive_mutex> lock(SqMtx);
    sq_pushroottable(v);
    sq_pushstring(v, _SC("Sq_SendPackToGateway"), -1);
    sq_newclosure(v, SquirrelSendMsg, 0); // create a new function
    sq_newslot(v, -3, SQFalse);
    sq_pop(v, 1); // pops the root table
}

static void *PackLogicThread(void *arg)
{
    while (true)
    {
        usleep(100);
        l_socket::getInstance().Logic();
    }

    // 在这里编写线程的具体操作

    pthread_exit(NULL);
}

void l_socket::InitPackLogic()
{
    pthread_t PackLogicT;
    int id1 = 1;
    // 创建线程1
    if (pthread_create(&PackLogicT, NULL, PackLogicThread, &id1) != 0)
    {
        std::cerr << "Error creating thread 1" << std::endl;
    }
}

void l_socket::Init(std::string Ip, std::string Port)
{
    InitSqr();
    asio::io_context io_context;
    ClientObj = new Client(io_context, Ip, Port);
    ClientObj->start();
    InitState = true;
    // InitPackLogic();
    io_context.run();
}

void l_socket::IntToByteLittle(unsigned char *b, int Count)
{
    b[0] = (Count & 0xff);
    b[1] = (Count & 0xff00) >> 8;
    b[2] = (Count & 0xff0000) >> 16;
    b[3] = (Count & 0xff000000) >> 24;
}

void l_socket::Send(const SQChar *Pck)
{
    if (ClientObj == nullptr || ClientObj->ConnectState == false)
        return;
    int Length = strlen(Pck);
    unsigned char *PckData = new unsigned char[Length + 4];
    IntToByteLittle(PckData, Length);
    memcpy(PckData + 4, Pck, Length);
    ClientObj->send(PckData, Length + 4);
    delete[] PckData;
}

void l_socket::Logic()
{
    if (ClientObj == nullptr)
        return;
    ClientObj->PackLogic();
}
