#include "../../../include/shared.hpp"
#include "include/controller_state.hpp"
#include <PSX/Periphery/periphery.hpp>

namespace ControllerTest {
    using namespace JabyEngine;

    static auto controller_state0 = ControllerState::create(Make::PositionI16(0,  0));
    static auto controller_state1 = ControllerState::create(Make::PositionI16(0, 76));

    static void setup() {
        Shared::back_menu.reset();
        controller_state0.setup();
        controller_state1.setup();
    }

    static bool update_or_exit() {
        Periphery::query_controller();
        if(Shared::back_menu.update(Make::PositionI16(0, GPU::Display::Height - 32))) {
            return true;
        }

        controller_state0.update(&Periphery::get_primary_controller_as<JabyEngine::Periphery::AnalogeController>(), FontWriter::bios_font_writer);
        controller_state1.update(Periphery::PortCount > 1 ? &Periphery::get_controller_as<JabyEngine::Periphery::AnalogeController>(1, 0) : nullptr, FontWriter::bios_font_writer);
        return false;
    }
    
    static void render() {
        GPU::render(Shared::background);
        controller_state0.render();
        controller_state1.render();
        FontWriter::bios_font_writer.render();
        Shared::back_menu.render();
    }

    void main() {
        setup();

        while(true) {
            if(update_or_exit()) {
                break;
            }
            GPU::swap_buffers_vsync(1);
            render();
        }
    }
}