#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);
    
    ImageBuffer::Get()->PushImage(ImageBuffer::IBType::Background, std::move(img_data), width, height, bit_depth);
    // Further processing of img_bytes can be done here
}

bool IpcMoudle::Initialize() {
    if (!initialize("ipc_sender", "ipc_sender")) {
        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;
    }
    return true;
}

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