#include "geometry.h"

#include <iostream>

void merge_objects(pangolin::Geometry &geometry, int &total_num_faces) {
    std::cout << geometry.objects.size() << " objects" << std::endl;
    geometry.textures.clear();

    total_num_faces = 0;
    for (const auto &object : geometry.objects) {
        auto vertext_indices = object.second.attributes.find("vertex_indices");
        if (vertext_indices != object.second.attributes.end()) {
            pangolin::Image<uint32_t> ibo =
                pangolin::get<pangolin::Image<uint32_t>>(
                    vertext_indices->second);

            total_num_faces += ibo.h;
        }
    }
    std::cout << total_num_faces << " faces" << std::endl;

    pangolin::ManagedImage<uint8_t> new_buffer(3 * sizeof(uint32_t),
                                               total_num_faces);
    pangolin::Image<uint32_t> new_ibo =
        new_buffer.UnsafeReinterpret<uint32_t>().SubImage(0, 0, 3,
                                                          total_num_faces);
    int new_index = 0;
    for (const auto &object : geometry.objects) {
        auto vertext_indices = object.second.attributes.find("vertex_indices");
        if (vertext_indices != object.second.attributes.end()) {
            pangolin::Image<uint32_t> ibo =
                pangolin::get<pangolin::Image<uint32_t>>(
                    vertext_indices->second);
            for (int k = 0; k < ibo.h; ++k) {
                new_ibo.Row(new_index).CopyFrom(ibo.Row(k));
                new_index++;
            }
        }
    }
    geometry.objects.clear();

    auto faces = geometry.objects.emplace(std::string("mesh"),
                                          pangolin::Geometry::Element());
    faces->second.Reinitialise(3 * sizeof(uint32_t), total_num_faces);
    faces->second.CopyFrom(new_buffer);
    new_ibo = faces->second.UnsafeReinterpret<uint32_t>().SubImage(
        0, 0, 3, total_num_faces);
    faces->second.attributes["vertex_indices"] = new_ibo;
}