#include <VirtualCamera.h>
#include <napi.h>

namespace VirtualCamera
{

    Napi::Value CreateVirturalCamera(const Napi::CallbackInfo &info)
    {
        Napi::Env env = info.Env();
        Napi::Number type = info[0].As<Napi::Number>();
        Napi::Number width = info[1].As<Napi::Number>();
        Napi::Number height = info[2].As<Napi::Number>();
        createVirturalCamera(type.Int32Value(), width.Int32Value(), height.Int32Value());
        return env.Undefined();
    }

    Napi::Value PushDataToVirturalCamera(const Napi::CallbackInfo &info)
    {
        Napi::Env env = info.Env();
        Napi::Buffer<char> raw = info[0].As<Napi::Buffer<char>>();
        Napi::Number width = info[1].As<Napi::Number>();
        Napi::Number height = info[2].As<Napi::Number>();
        uint8_t *data = (uint8_t *)malloc(raw.Length());
        for (int i = 0; i < height.Int32Value(); i++)
        {
            int pos_1 = i * width.Int32Value() * 4;
            int pos_2 = (height.Int32Value() - i - 1) * width.Int32Value() * 4;
            memcpy((void *)(data + pos_1), (void *)(raw.Data() + pos_2), width.Int32Value() * 4);
        }
        pushDataToVirturalCamera(data, width.Int32Value(), height.Int32Value());
        free(data);
        return env.Undefined();
    }

    Napi::Value ChangeResolutionOfVirturalCamera(const Napi::CallbackInfo &info)
    {
        Napi::Env env = info.Env();
        Napi::Number width = info[0].As<Napi::Number>();
        Napi::Number height = info[1].As<Napi::Number>();
        changeResolutionOfVirturalCamera(width.Int32Value(), height.Int32Value());
        return env.Undefined();
    }
} // namespace NAMA

Napi::Object Init(Napi::Env env, Napi::Object exports)
{
    exports.Set(Napi::String::New(env, "createVirturalCamera"), Napi::Function::New(env, VirtualCamera::CreateVirturalCamera));
    exports.Set(Napi::String::New(env, "pushDataToVirturalCamera"), Napi::Function::New(env, VirtualCamera::PushDataToVirturalCamera));
    exports.Set(Napi::String::New(env, "changeResolutionOfVirturalCamera"), Napi::Function::New(env, VirtualCamera::ChangeResolutionOfVirturalCamera));
    return exports;
}

NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init);