#include "game_input.h"

#include <bitset>
#include <stdio.h>

bool handle_input_frame(InputContext &ctx) {
    scanKeys();
    const int keys = keysDown();

    if (keys && *ctx.internals) {
        consoleSelect(ctx.topScreen);
        iprintf("\x1b[6;0Hkeys = %s", std::bitset<16>(keys).to_string().c_str());
    }

    if ((keys & KEY_START) && (keys & KEY_L)) {
        return false;
    }

    if (keys & KEY_SELECT) {
        *ctx.internals = !(*ctx.internals);
        if (*ctx.internals) {
            setBackdropColor(RGB15(0, 0, 7));
        } else {
            setBackdropColor(RGB15(0, 0, 0));
            consoleSelect(ctx.topScreen);
            consoleClear();
        }
    }

    if (!ctx.state->paused && !ctx.state->gameOver) {
        if (keys & KEY_UP) {
            ctx.state->snakeDirection = 0;
            draw_game(*ctx.state, *ctx.renderAssets);
        }

        if (keys & KEY_RIGHT) {
            ctx.state->snakeDirection = 1;
            draw_game(*ctx.state, *ctx.renderAssets);
        }

        if (keys & KEY_DOWN) {
            ctx.state->snakeDirection = 2;
            draw_game(*ctx.state, *ctx.renderAssets);
        }

        if (keys & KEY_LEFT) {
            ctx.state->snakeDirection = 3;
            draw_game(*ctx.state, *ctx.renderAssets);
        }
    }

    if (ctx.state->paused) {
        if (keys & KEY_X) {
            audio_toggle_music(*ctx.audio);
        }

        if (keys & KEY_Y) {
            ctx.state->hardMode = !ctx.state->hardMode;
            ctx.init_game();
            draw_game(*ctx.state, *ctx.renderAssets);
        }
    }

    if (keys & KEY_R) {
        lcdSwap();
    }

    if (keys & KEY_START) {
        if (!ctx.state->gameOver) {
            ctx.state->paused = !ctx.state->paused;

            if (ctx.state->paused) {
                consoleSelect(ctx.topScreen);
                audio_play_pause(*ctx.audio);
                audio_pause_music_if_enabled(*ctx.audio);
                iprintf("\x1b[11;12HPaused");
            } else {
                audio_resume_music_if_enabled(*ctx.audio);
                audio_play_unpause(*ctx.audio);
                consoleSelect(ctx.topScreen);
                consoleClear();
            }
        } else {
            ctx.init_game();
        }
    }

    return true;
}
