#include <PSX/System/IOPorts/interrupt_io.hpp>
#include <PSX/System/syscalls.hpp>
#include <PSX/Timer/high_res_timer.hpp>

namespace JabyEngine {
    namespace Timer {
        extern SysCall::InterruptCallback irq_callback;
    }

    namespace boot {
        namespace Timer {
            using namespace JabyEngine::Timer;
            
            void setup() {
                using namespace Timer_IO;
                using namespace Timer_IO_Values;

                static constexpr auto Mode = CounterMode::from(CounterMode::FreeRun, Counter2::SyncMode::FreeRun, CounterMode::ResetAfterTarget, CounterMode::IRQAtTarget, CounterMode::IRQEveryTime, CounterMode::IRQPulse, Counter2::Source::System_Clock_Div_8);

                // We disable the IRQ here so it can be enabled by user demand later
                // Having the interrupt fire every 10ms will slow us down slightly so we only do it on demand
                Interrupt::disable_irq(Interrupt::Timer2);

                SysCall::EnterCriticalSection();
                    SysCall::SysEnqIntRP(SysCall::Priority::Timer2Irq, &irq_callback);
                SysCall::ExitCriticalSection();

                Counter2.set_target_value(HighResTime::TicksFor10ms);
                Counter2.set_mode(Mode);
            }
        }
    }
}