#include <string>
#include <vector>
#include <cstdlib>

#include "doctest.h"
#include "../libs/lodepng/lodepng.h"

#include "../source/vm.h"
#include "../source/host.h"
#include "../source/hostVmShared.h"
#include "../source/nibblehelpers.h"
#include "stubhost.h"

// Renders the BIOS cart's file browser. With FAKE08_BIOS_PNG set, the screen
// is also written to that file (for looking at the layout).
TEST_CASE("bios file browser") {
    stubDirList = {"zeta", "alpha"};
    stubCartList = {"carts/celeste.p8.png", "carts/a_rather_long_cart_name_that_needs_cutting.p8", "carts/b.p8"};
    for (int i = 0; i < 20; i++) stubCartList.push_back("carts/cart" + std::to_string(i) + ".p8");

    StubHost* host = new StubHost();
    Vm* vm = new Vm(host);
    vm->SetCartList(stubCartList);   // as main() does
    vm->LoadBiosCart();
    vm->vm_run();
    for (int i = 0; i < 5; i++) {
        host->stubInput(0, 0);
        vm->Step();
    }

    CHECK(vm->GetBiosError() == "");

    // the selection bar (text colour, 7) starts on the first cart: row 3
    // (.., alpha, zeta, then carts), y = 19 + 3 * 6 - 1
    uint8_t* fb = vm->GetPicoInteralFb();
    CHECK(getPixelNibble(64, 19 + 3 * 6 - 1, fb) == 7);

    if (const char* out = getenv("FAKE08_BIOS_PNG")) {
        uint8_t* map = vm->GetScreenPaletteMap();
        host->setUpPaletteColors();
        Color* colors = host->GetPaletteColors();
        std::vector<unsigned char> image(128 * 128 * 4);
        for (int y = 0; y < 128; y++)
            for (int x = 0; x < 128; x++) {
                Color c = colors[map[getPixelNibble(x, y, fb)] & 0x8f];
                size_t i = (y * 128 + x) * 4;
                image[i] = c.Red; image[i + 1] = c.Green; image[i + 2] = c.Blue; image[i + 3] = 255;
            }
        lodepng::encode(out, image, 128, 128);
    }

    stubDirList.clear();
    stubCartList.clear();
    delete vm;
    delete host;
}
