// Runtime check 3: CPU-drawn frames through the title's own GPU ring
// (xex_video) and controller input (xex_input). Moving gradient, a square
// moved with the d-pad/left stick, A/B/X/Y change its colour, a bar shows
// the frame rate. The Xbox button opens the Guide (Xbox Home leaves);
// Back+Start returns to the dashboard.
#include <cstdio>
#include <cstdint>
#include <cstdarg>

#include "xex_runtime.h"
#include "xex_video.h"
#include "xex_input.h"

// Diagnostics: every trace line is appended to game:/video-log.txt (the
// file is closed after each line so it survives a hang).
static void logLine(const char *fmt, ...) {
    char line[256];
    va_list ap;
    va_start(ap, fmt);
    vsnprintf(line, sizeof line, fmt, ap);
    va_end(ap);
    printf("video: %s\n", line);
    if (FILE *f = fopen("game:/video-log.txt", "a")) {
        fprintf(f, "%s\n", line);
        fclose(f);
    }
}

static const char *const buttonNames[16] = {
    "UP", "DOWN", "LEFT", "RIGHT", "START", "BACK", "LTHUMB", "RTHUMB",
    "LB", "RB", "bit10", "bit11", "A", "B", "X", "Y"};

// Logs every change of a controller: buttons by name, triggers past half,
// sticks past half in each direction.
static void logPadChanges(int port, int connected, const xex_pad &pad) {
    static int lastConnected[4] = {-2, -2, -2, -2};
    static xex_pad last[4];
    if (connected != lastConnected[port]) {
        logLine("pad %d: %s", port, connected == 0 ? "connected" : "not connected");
        lastConnected[port] = connected;
    }
    if (connected != 0) return;
    uint16_t changed = pad.buttons ^ last[port].buttons;
    for (int b = 0; b < 16; b++) {
        if (changed & (1 << b))
            logLine("pad %d: %s %s", port, buttonNames[b], (pad.buttons & (1 << b)) ? "down" : "up");
    }
    auto zone = [](int v) { return v > 16000 ? 1 : v < -16000 ? -1 : 0; };
    const int16_t now[4] = {pad.lx, pad.ly, pad.rx, pad.ry};
    const int16_t before[4] = {last[port].lx, last[port].ly, last[port].rx, last[port].ry};
    static const char *const axis[4] = {"left stick x", "left stick y", "right stick x", "right stick y"};
    for (int a = 0; a < 4; a++) {
        if (zone(now[a]) != zone(before[a])) logLine("pad %d: %s %d (%s)", port, axis[a], now[a],
                                                     zone(now[a]) > 0 ? "+" : zone(now[a]) < 0 ? "-" : "centre");
    }
    if ((pad.left_trigger > 128) != (last[port].left_trigger > 128))
        logLine("pad %d: LT %u", port, pad.left_trigger);
    if ((pad.right_trigger > 128) != (last[port].right_trigger > 128))
        logLine("pad %d: RT %u", port, pad.right_trigger);
    last[port] = pad;
}

int main(int, char **) {
    remove("game:/video-log.txt");
    logLine("start");
    xex_video_trace = logLine;
    xex_video_dump_registers("before init");
    if (xex_video_init() != 0) {
        logLine("init failed: %s", xex_video_error());
        xex_notify("video init failed");
        xex_sleep_ms(4000);
        return 1;
    }

    int sx = 200, sy = 200;
    uint32_t colour = xex_video_rgb(255, 0, 77);
    uint64_t freq = xex_timebase_freq();
    uint64_t last = xex_timebase(), second = last;
    int frames = 0, fps = 0;
    unsigned t = 0;

    logLine("init ok");
    xex_video_dump_registers("after init");
    uint64_t startTime = xex_timebase();
    int seconds = 0;
    for (;;) {
        xex_pad pad;
        int connected = xex_input_get(0, &pad);
        logPadChanges(0, connected, pad);
        for (int port = 1; port < 4; port++) {
            xex_pad other;
            logPadChanges(port, xex_input_get(port, &other), other);
        }
        // stop by itself after 20 s, so a black screen still tells whether the loop runs
        // never end by ourselves while the Guide shows: XAM would wait for a
        // swap that never comes
        if (xex_timebase() - startTime > 60 * freq && !xex_video_guide_visible()) {
            logLine("60 s elapsed, exiting");
            break;
        }
        if ((pad.buttons & XEX_PAD_BACK) && (pad.buttons & XEX_PAD_START)) break;

        int speed = 6;
        if ((pad.buttons & XEX_PAD_LEFT) || pad.lx < -12000) sx -= speed;
        if ((pad.buttons & XEX_PAD_RIGHT) || pad.lx > 12000) sx += speed;
        if ((pad.buttons & XEX_PAD_UP) || pad.ly > 12000) sy -= speed;
        if ((pad.buttons & XEX_PAD_DOWN) || pad.ly < -12000) sy += speed;
        if (pad.buttons & XEX_PAD_A) colour = xex_video_rgb(0, 228, 54);
        if (pad.buttons & XEX_PAD_B) colour = xex_video_rgb(255, 0, 77);
        if (pad.buttons & XEX_PAD_X) colour = xex_video_rgb(41, 173, 255);
        if (pad.buttons & XEX_PAD_Y) colour = xex_video_rgb(255, 236, 39);

        xex_frame f = xex_video_begin();
        if (sx < 0) sx = 0;
        if (sy < 0) sy = 0;
        if (sx > f.window_width - 128) sx = f.window_width - 128;
        if (sy > f.window_height - 128) sy = f.window_height - 128;

        for (int y = 0; y < f.window_height; y++) {
            int py = f.window_y + y;
            for (int x = 0; x < f.window_width; x++) {
                uint32_t c;
                if (x >= sx && x < sx + 128 && y >= sy && y < sy + 128) {
                    c = colour;
                } else if (y >= f.window_height - 40 && y < f.window_height - 16 && x >= 16 &&
                           x < 16 + 16 * 36 && (x - 16) % 36 < 30) {
                    int b = (x - 16) / 36;
                    c = (pad.buttons & (1 << b)) ? xex_video_rgb(255, 255, 255) : xex_video_rgb(40, 40, 40);
                } else if (y >= f.window_height - 64 && y < f.window_height - 52 &&
                           ((x >= 16 && x < 16 + pad.left_trigger) ||
                            (x >= 320 && x < 320 + pad.right_trigger))) {
                    c = xex_video_rgb(255, 163, 0);
                } else if (y < 24 && x < fps * 8) {
                    c = xex_video_rgb(255, 255, 255);
                } else {
                    c = xex_video_rgb((uint8_t)(x + t), (uint8_t)(y + t / 2), 96);
                }
                f.pixels[xex_video_tiled_index(f.window_x + x, py, f.pitch)] = c;
            }
        }
        xex_video_present();
        t += 2;

        frames++;
        uint64_t now = xex_timebase();
        if (now - second >= freq) {
            fps = frames;
            logLine("second %d: %d fps, %dx%d window at %d,%d, pad %s buttons %04x",
                    ++seconds, fps, f.window_width, f.window_height, f.window_x, f.window_y,
                    connected == 0 ? "ok" : "none", pad.buttons);
            if (seconds == 2) {
                xex_video_dump_registers("running");
                xex_video_dump_lut();
            }
            frames = 0;
            second = now;
        }
        last = now;
    }
    (void)last;
    logLine("exit");
    return 0;
}
