#include <iostream>
#include <emscripten/emscripten.h>

extern "C" {
    int worker_function(int* faces, int nfaces, float* verts, int nverts);
    int worker_function2(void* verts, int size);

}

std::string hexcode(unsigned char byte) {
    const static char codes[] = "0123456789abcdef_";
    std::string result = codes[(byte/16) % 16] + ( codes[byte % 16] + std::string());
    return std::string(result = codes[(byte/16) % 16] + ( codes[byte % 16] + std::string()));
}

template <typename T>
void dump(T* elements, int size_bytes, std::string type_name) {
    std::cout << "As "+type_name+": ";
    T* typed_data = (T*)elements;
    size_t typed_size = (size_bytes + sizeof(T)-1) / sizeof(T);
    for (size_t i = 0; i < typed_size; ++i) {
        std::cout << typed_data[i] << " ";
    }
    std::cout << std::endl;
}

void dump_hex(char* data, int size_bytes) {
    std::cout << "As bytes: ";
    size_t i = 0 ;
    char* char_data = (char*)data;
    for (; i < size_bytes; ++i) {
        std::cout << hexcode((char_data)[i]) << " ";
    }
    std::cout << "(end)";
    for (; i < size_bytes; ++i) {
        std::cout << hexcode((char_data)[i]) << " ";
    }
    std::cout << std::endl;
}

int worker_function(int* faces, int nfaces, float* verts, int nverts) {
    /*
    dump_hex((char*)data, size);
    dump<unsigned char>(data, size, "byte");
    dump<float>(data, size, "float");
    dump<double>(data, size, "double");
    */
    dump<int>(faces, nfaces*sizeof(int), "int");
    dump<float>(verts, nverts*sizeof(float), "float");

    return 311;

    //Reporting back:
    int total_size = nfaces*sizeof(int) + nverts*sizeof(float);
    // emscripten_worker_respond_provisionally(0, 0);
    //emscripten_worker_respond(0, 0);
    //emscripten_worker_respond(static_cast<char*>(static_cast<void*>(static_datum.data())), static_cast<int>(sizeof(static_datum)));
    std::string result = std::string("I received ") + std::to_string(total_size) + " bytes.";
    //emscripten_worker_respond((void*)(result.data()), result.size());
    char* resstr = (char*)result.c_str();
    emscripten_worker_respond(resstr, result.size());
    //return result.c_str();
    return 314;
}

int worker_function2(void* verts, int size) {
    return 128;
}
int main(){return 0;}
