#include "Ipc/IpcMoudle.h"

#include <iostream>

#define STB_IMAGE_WRITE_IMPLEMENTATION
#include <stb/stb_image_write.h>

#include "Core/Core.h"
#include "Ipc/ipclib.h"
#include "ImageBuffer.h"

IpcMoudle* Singleton<IpcMoudle>::instance_ = nullptr;

void OnParseImageData(const char* data, size_t size) {
    if (size < 13) { // Minimum size check: 1 byte identifier + 4 bytes width + 4 bytes height + 4 bytes bit depth
        std::cerr << "Invalid data size" << std::endl;
        return;
    }

    // Extract identifier
    char identifier = data[0];

    // Extract width
    int width;
    std::memcpy(&width, data + 1, sizeof(int));

    // Extract height
    int height;
    std::memcpy(&height, data + 5, sizeof(int));

    // Extract bit depth
    int bit_depth;
    std::memcpy(&bit_depth, data + 9, sizeof(int));

    // Extract image bytes
    const char* img_bytes = data + 13;
    size_t img_size = size - 13;
    std::vector<uint8> img_data(img_size);
    memcpy(img_data.data(), img_bytes, img_size);
    
    if (0x01 == identifier) {
        ImageBuffer::Get()->PushImage(ImageBuffer::IBType::Human, std::move(img_data), width, height, bit_depth);
    } else if (0x02 == identifier) {
        ImageBuffer::Get()->PushImage(ImageBuffer::IBType::Face, std::move(img_data), width, height, bit_depth);
    } else if (0x03 == identifier) {
        ImageBuffer::Get()->PushImage(ImageBuffer::IBType::FaceMask, std::move(img_data), width, height, bit_depth);
    }
}

bool IpcMoudle::Initialize() {
    if (!initialize("human_render", "human_product")) {
        ERRORLOG("ipc initialize failed");
        return false;
    }

    setReaderCallback([](const char* data, unsigned int size) {
        //INFOLOG("ipc recive data:{}", size);
        OnParseImageData(data, size);
        }
    );

    if (!listen()) {
        ERRORLOG("ipc listen failed");
        return false;
    }
    lastHeartbeatTime_ = std::chrono::steady_clock::now();
    return true;
}

void IpcMoudle::Uninitialize() {
    uninitialize();
}

bool IpcMoudle::Send(const char* data, unsigned int size) {
    return send(data, size);
}

void IpcMoudle::OnFrame() {
    auto now = std::chrono::steady_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::seconds>(now - lastHeartbeatTime_);

    if (duration.count() >= 2) {
        constexpr char heartbeat[] = "heartbeat";
        if (!send("heartbeat", sizeof(heartbeat) / sizeof(heartbeat[0]))) {
            ERRORLOG("send heartbeat failed");
            reConnect();
        }
        lastHeartbeatTime_ = now;
    }
}
