#include "pack.h"

#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstring>
#include <iostream>

namespace freling {

void blit(const Frame& in_frame,
          const BoundingBox& in_box,
          Frame& out_frame,
          const BoundingBox& out_box) {
    assert(in_box.width == out_box.width);
    assert(in_box.height == out_box.height);

    const int data_width = in_box.width * sizeof(Pixel);
    const int in_row_size = in_frame.width;
    const int out_row_size = out_frame.width;

    for (unsigned int i = 0; i < in_box.height; ++i) {
        const int in_offset = in_box.x + (i + in_box.y) * in_row_size;
        const int out_offset = out_box.x + (i + out_box.y) * out_row_size;

        memcpy(out_frame.data + out_offset, in_frame.data + in_offset,
               data_width);
    }
}

std::optional<Frame> pack(const Frame& in_frame,
                          const std::vector<BoundingBox>& bboxes,
                          std::vector<BoundingBox>& packed_bboxes) {
    if (bboxes.size() == 0) {
        std::cerr << "No bounding box, cannot pack.\n";
        return {};
    }
    // We sort the bounding boxes by height
    std::vector<BoundingBox> sorted_bboxes = bboxes;
    std::sort(sorted_bboxes.begin(), sorted_bboxes.end(),
              [](const auto& a, const auto& b) { return a.height > b.height; });

    // We keep a mapping between the sorted bounding boxes and the original
    // order
    std::vector<int> mapping(bboxes.size());
    for (int i = 0; i < sorted_bboxes.size(); ++i) {
        const auto& s_box = sorted_bboxes[i];
        for (int j = 0; j < bboxes.size(); ++j) {
            const auto& box = bboxes[j];
            if (box == s_box) {
                mapping[i] = j;
                continue;
            }
        }
    }

    int max_area = 0;
    for (const auto& box : sorted_bboxes) {
        int area = box.area();
        max_area += area;
    }
    std::cout << "[pack] max area: " << max_area << "\n";
    int optimal_size = int(ceil(std::sqrt(max_area)));
    std::cout << "[pack] optimal image dimention: " << optimal_size << " x "
              << optimal_size << "\n";

    // cf. subject: D < min(M, N )
    const int max_size = std::min(in_frame.width, in_frame.height) - 1;
    std::cout << "[pack] maximum image dimention: " << max_size << " x "
              << max_size << "\n";

    // We will try to fit all the rectangles in a given square of size S.
    // optimal_size <= S <= max_size (smallest dimension of input frame)
    // To find S, we will generate N candidates and try to fit everything.
    const int nb_candidates = 5;
    const int size_increment = (max_size - optimal_size) / nb_candidates;
    for (int size = optimal_size; size <= max_size; size += size_increment) {
        std::cout << "[pack] trying to fit in " << size << " x " << size
                  << "\n";
        int x = 0;
        int y = 0;
        int next_row = 0;
        bool room_left = true;

        for (int box_i = 0, box_max = bboxes.size();
             room_left and box_i < box_max; ++box_i) {
            auto& box = sorted_bboxes[box_i];
            std::cout << "[pack]  box " << box.width << " x " << box.height
                      << "\n";

            // If we don't have room in either dimension, we won't be able to
            // pack within this size candidate.
            if (x + box.width >= size and next_row + box.height >= size) {
                std::cout << "[pack]   -> no room left (last row height = "
                          << size - y << ")\n";
                room_left = false;
                continue;
            }

            // If we cannot fit the rect on the right, we fit it below.
            if (x + box.width >= size) {
                std::cout
                    << "[pack]   -> cannot fit in current row (width left = "
                    << size - x << ")\n";
                x = 0;
                y = next_row;
            }

            // If we add a box in a new row, we bump the next row index.
            // Because we previously sorted the rectangles by height, we
            // know the next ones won't cross this line.
            if (x == 0) {
                next_row = box.height;
                std::cout << "[pack]   -> create new row at line " << y << "\n";
            }

            box.x = x;
            box.y = y;
            x += box.width;
            std::cout << "[pack]   -> fit in (" << x << ", " << y << ")\n";
        }

        if (room_left) {
            Frame packed_frame(size, size);
            packed_frame.fill(0);

            packed_bboxes.resize(bboxes.size());
            for (int i = 0; i < mapping.size(); ++i) {
                int box_index = mapping[i];
                packed_bboxes[box_index] = sorted_bboxes[i];
                blit(in_frame, bboxes[box_index], packed_frame,
                     sorted_bboxes[i]);
            }

            return packed_frame;
        }
    }

    std::cerr << "Cannot pack rectangles.\n";
    return {};
}

}  // namespace freling
