/**
 * @file console_verbs.c
 * @brief Tests the group E verbs: SLEEP, WAIT, KEY, WINDOW and the TI clock.
 *
 * The two that wait are the interesting ones, and what they have to prove is
 * that they *do not block*: a held step still returns, so a bounded
 * akbasic_runtime_run() comes back on time and a host keeps its frame rate.
 * Section 1.6 is the rule and this is where it is checked for group E.
 */

#include <string.h>

#include <akbasic/error.h>
#include <akbasic/runtime.h>

#include "harness.h"
#include "testutil.h"

/** @brief Load a program and put the runtime in RUN mode without stepping it. */
static akerr_ErrorContext AKERR_NOIGNORE *load_program(const char *source)
{
    PREPARE_ERROR(errctx);

    PASS(errctx, harness_start(NULL));
    PASS(errctx, akbasic_runtime_load(&HARNESS_RUNTIME, source));
    PASS(errctx, akbasic_runtime_start(&HARNESS_RUNTIME, AKBASIC_MODE_RUN));
    SUCCEED_RETURN(errctx);
}

/** @brief Run a program to completion in RUN mode. */
static akerr_ErrorContext AKERR_NOIGNORE *run_program(const char *source)
{
    PREPARE_ERROR(errctx);

    PASS(errctx, load_program(source));
    PASS(errctx, akbasic_runtime_run(&HARNESS_RUNTIME, 0));
    SUCCEED_RETURN(errctx);
}

/** @brief SLEEP holds the step loop until the host's clock passes its deadline. */
static void test_sleep(void)
{
    TEST_REQUIRE_OK(load_program("1 PRINT \"BEFORE\"\n"
				 "2 SLEEP 5\n"
				 "3 PRINT \"AFTER\"\n"));
    TEST_REQUIRE_OK(akbasic_runtime_settime(&HARNESS_RUNTIME, 1000));

    /* Line 0, line 1, line 2 -- the SLEEP arms and the program stops advancing. */
    TEST_REQUIRE_OK(akbasic_runtime_run(&HARNESS_RUNTIME, 3));
    TEST_REQUIRE_STR(HARNESS_OUTPUT, "BEFORE\n");
    TEST_REQUIRE(HARNESS_RUNTIME.console_state.sleeping, "SLEEP should be holding");

    /*
     * Twenty more steps with the clock standing still change nothing -- and,
     * crucially, they *return*. A SLEEP that blocked would never get here.
     */
    TEST_REQUIRE_OK(akbasic_runtime_run(&HARNESS_RUNTIME, 20));
    TEST_REQUIRE_STR(HARNESS_OUTPUT, "BEFORE\n");

    /* Past the deadline, it wakes. */
    TEST_REQUIRE_OK(akbasic_runtime_settime(&HARNESS_RUNTIME, 6500));
    TEST_REQUIRE_OK(akbasic_runtime_run(&HARNESS_RUNTIME, 2));
    TEST_REQUIRE_STR(HARNESS_OUTPUT, "BEFORE\nAFTER\n");
    TEST_REQUIRE(!HARNESS_RUNTIME.console_state.sleeping, "SLEEP should have finished");
    harness_stop();
}

/** @brief A host that never sets a clock does not hang on SLEEP. */
static void test_sleep_without_a_clock(void)
{
    TEST_REQUIRE_OK(run_program("1 SLEEP 10\n2 PRINT \"THROUGH\"\n"));
    TEST_REQUIRE_STR(HARNESS_OUTPUT, "THROUGH\n");
    harness_stop();
}

/** @brief SLEEP refuses a negative interval rather than waiting forever. */
static void test_sleep_refuses_negative(void)
{
    TEST_REQUIRE_OK(run_program("10 SLEEP -1\n"));
    TEST_REQUIRE(strstr(HARNESS_OUTPUT, "negative number of seconds") != NULL,
		 "SLEEP -1 should be refused, got \"%s\"", HARNESS_OUTPUT);
    harness_stop();
}

/**
 * @brief WAIT polls a byte and holds until it matches, without blocking.
 *
 * The address is a real one -- this test's own variable -- which is the only
 * honest way to exercise it: on a C128 the byte is a hardware register, and here
 * the only thing that can change it is something outside the program.
 */
static void test_wait(void)
{
    static volatile uint8_t watched = 0;
    char source[256];

    watched = 0;
    snprintf(source, sizeof(source),
	     "1 WAIT %llu, 1\n2 PRINT \"RELEASED\"\n",
	     (unsigned long long)(uintptr_t)&watched);

    TEST_REQUIRE_OK(load_program(source));
    TEST_REQUIRE_OK(akbasic_runtime_run(&HARNESS_RUNTIME, 4));
    TEST_REQUIRE_STR(HARNESS_OUTPUT, "");
    TEST_REQUIRE(HARNESS_RUNTIME.console_state.waiting, "WAIT should be holding");

    /* Still returning, which is the whole point. */
    TEST_REQUIRE_OK(akbasic_runtime_run(&HARNESS_RUNTIME, 20));
    TEST_REQUIRE_STR(HARNESS_OUTPUT, "");

    watched = 1;
    TEST_REQUIRE_OK(akbasic_runtime_run(&HARNESS_RUNTIME, 2));
    TEST_REQUIRE_STR(HARNESS_OUTPUT, "RELEASED\n");
    harness_stop();
}

/** @brief KEY stores a macro per key, and bare KEY lists all eight. */
static void test_key(void)
{
    TEST_REQUIRE_OK(run_program("10 KEY 1, \"RUN\"\n"
				"20 KEY 3, \"LIST\"\n"
				"30 KEY\n"));
    TEST_REQUIRE(strstr(HARNESS_OUTPUT, "KEY 1, \"RUN\"") != NULL,
		 "KEY should list its macros, got \"%s\"", HARNESS_OUTPUT);
    TEST_REQUIRE(strstr(HARNESS_OUTPUT, "KEY 3, \"LIST\"") != NULL,
		 "KEY should list its macros, got \"%s\"", HARNESS_OUTPUT);
    TEST_REQUIRE(strstr(HARNESS_OUTPUT, "KEY 8, \"\"") != NULL,
		 "KEY should list undefined keys too, got \"%s\"", HARNESS_OUTPUT);
    harness_stop();

    TEST_REQUIRE_OK(run_program("10 KEY 9, \"NOPE\"\n"));
    TEST_REQUIRE(strstr(HARNESS_OUTPUT, "outside 1..8") != NULL,
		 "KEY 9 should be refused, got \"%s\"", HARNESS_OUTPUT);
    harness_stop();
}

/** @brief WINDOW refuses against a sink with no character grid, which is stdio. */
static void test_window_needs_a_grid(void)
{
    TEST_REQUIRE_OK(run_program("10 WINDOW 1, 1, 20, 10\n"));
    TEST_REQUIRE(strstr(HARNESS_OUTPUT, "character grid") != NULL,
		 "WINDOW against a stdio sink should refuse by name, got \"%s\"",
		 HARNESS_OUTPUT);
    harness_stop();

    /* An inside-out rectangle is refused before the device is even consulted. */
    TEST_REQUIRE_OK(run_program("10 WINDOW 20, 10, 1, 1\n"));
    TEST_REQUIRE(strstr(HARNESS_OUTPUT, "bottom right") != NULL,
		 "an inverted WINDOW should be refused, got \"%s\"", HARNESS_OUTPUT);
    harness_stop();
}

/*
 * A grid a stdio sink does not have.
 *
 * `RWINDOW` and `RGR(3)`/`RGR(4)` read the sink's grid, and the harness sink is
 * stdio, which has none -- so without a stand-in the only thing assertable here
 * is the refusal. This is the akgl sink's shape without the SDL: the runtime
 * asks through a function pointer and does not care who answers.
 *
 * Windowing changes the columns and rows and leaves the cell size alone, which
 * is the distinction RWINDOW and RGR are split across, so the fake honours it.
 */
static int FAKE_COLUMNS = 50;
static int FAKE_ROWS = 37;

static akerr_ErrorContext AKERR_NOIGNORE *fake_grid(akbasic_TextSink *self, int *columns, int *rows, int *cellw, int *cellh)
{
    PREPARE_ERROR(errctx);

    (void)self;
    FAIL_ZERO_RETURN(errctx, (columns != NULL && rows != NULL && cellw != NULL && cellh != NULL),
		     AKERR_NULLPOINTER, "NULL destination in fake grid");
    *columns = FAKE_COLUMNS;
    *rows = FAKE_ROWS;
    *cellw = 16;
    *cellh = 16;
    SUCCEED_RETURN(errctx);
}

static akerr_ErrorContext AKERR_NOIGNORE *fake_window(akbasic_TextSink *self, int left, int top, int right, int bottom)
{
    PREPARE_ERROR(errctx);

    (void)self;
    FAKE_COLUMNS = (right - left) + 1;
    FAKE_ROWS = (bottom - top) + 1;
    SUCCEED_RETURN(errctx);
}

/**
 * @brief `RWINDOW` and the cell-size `RGR` fields report the grid.
 *
 * A program had no way to ask how big a character is, so anything placing a
 * character *and* a sprite at the same spot hardcoded a cell size measured
 * against whatever font the host loaded. The Breakout in `examples/` did, and it
 * was the one thing in that listing that broke on a different window. TODO.md
 * section 6 item 31.
 */
static void test_rwindow(void)
{
    /* Without a grid, both refuse by name rather than answering something. */
    TEST_REQUIRE_OK(run_program("10 PRINT RWINDOW(0)\n"));
    TEST_REQUIRE(strstr(HARNESS_OUTPUT, "character grid") != NULL,
		 "RWINDOW against a stdio sink should refuse by name, got \"%s\"",
		 HARNESS_OUTPUT);
    harness_stop();

    FAKE_COLUMNS = 50;
    FAKE_ROWS = 37;
    TEST_REQUIRE_OK(load_program("10 PRINT RWINDOW(0)\n"
				 "20 PRINT RWINDOW(1)\n"
				 "30 PRINT RGR(3)\n"
				 "40 PRINT RGR(4)\n"));
    HARNESS_SINK.grid = fake_grid;
    TEST_REQUIRE_OK(akbasic_runtime_run(&HARNESS_RUNTIME, 0));
    /* Rows first: that is RWINDOW's own order on a C128, and it is not obvious. */
    TEST_REQUIRE_STR(HARNESS_OUTPUT, "37\n50\n16\n16\n");
    harness_stop();

    /* RWINDOW follows a WINDOW; the cell size does not, because windowing does
       not change how big a character is. */
    FAKE_COLUMNS = 50;
    FAKE_ROWS = 37;
    TEST_REQUIRE_OK(load_program("10 WINDOW 0, 0, 19, 4\n"
				 "20 PRINT RWINDOW(1)\n"
				 "30 PRINT RWINDOW(0)\n"
				 "40 PRINT RGR(3)\n"));
    HARNESS_SINK.grid = fake_grid;
    HARNESS_SINK.window = fake_window;
    TEST_REQUIRE_OK(akbasic_runtime_run(&HARNESS_RUNTIME, 0));
    TEST_REQUIRE_STR(HARNESS_OUTPUT, "20\n5\n16\n");
    HARNESS_SINK.window = NULL;
    harness_stop();

    /*
     * Field 2 is refused by name. A C128 answers 0 for 40-column mode and 1 for
     * 80-column; this interpreter has neither, and answering 0 would be a
     * plausible lie -- which is worse than a refusal that says why.
     */
    FAKE_COLUMNS = 50;
    FAKE_ROWS = 37;
    TEST_REQUIRE_OK(load_program("10 PRINT RWINDOW(2)\n"));
    HARNESS_SINK.grid = fake_grid;
    TEST_REQUIRE_OK(akbasic_runtime_run(&HARNESS_RUNTIME, 0));
    TEST_REQUIRE(strstr(HARNESS_OUTPUT, "40 or 80 column mode") != NULL,
		 "RWINDOW(2) should be refused by name, got \"%s\"", HARNESS_OUTPUT);
    harness_stop();

    TEST_REQUIRE_OK(load_program("10 PRINT RWINDOW(7)\n"));
    HARNESS_SINK.grid = fake_grid;
    TEST_REQUIRE_OK(akbasic_runtime_run(&HARNESS_RUNTIME, 0));
    TEST_REQUIRE(strstr(HARNESS_OUTPUT, "outside 0..1") != NULL,
		 "RWINDOW(7) should be out of range, got \"%s\"", HARNESS_OUTPUT);
    harness_stop();
}

/** @brief TI# counts jiffies and TI$ formats them, both from the host's clock. */
static void test_ti(void)
{
    TEST_REQUIRE_OK(load_program("1 PRINT TI#\n2 PRINT TI$\n"));
    /* 3661 seconds is 01:01:01, and 3661 * 60 jiffies. */
    TEST_REQUIRE_OK(akbasic_runtime_settime(&HARNESS_RUNTIME, 3661000));
    TEST_REQUIRE_OK(akbasic_runtime_run(&HARNESS_RUNTIME, 3));
    TEST_REQUIRE_STR(HARNESS_OUTPUT, "219660\n010101\n");
    harness_stop();

    /* A host with no clock has a stopped one rather than a wrong one. */
    TEST_REQUIRE_OK(run_program("1 PRINT TI$\n"));
    TEST_REQUIRE_STR(HARNESS_OUTPUT, "000000\n");
    harness_stop();
}

int main(void)
{
    test_sleep();
    test_sleep_without_a_clock();
    test_sleep_refuses_negative();
    test_wait();
    test_key();
    test_window_needs_a_grid();
    test_rwindow();
    test_ti();
    return akbasic_test_failures;
}
