#include "../../internal-include/BootLoader/boot_loader.hpp"
#include "../../internal-include/CD/cd_internal.hpp"
#include <PSX/System/IOPorts/interrupt_io.hpp>
#include <PSX/System/IOPorts/memory_io.hpp>
#include <PSX/System/syscalls.hpp>

namespace JabyEngine {
    namespace CD {
        namespace internal {
            extern SysCall::InterruptCallback irq_callback;
        }
    }
    
    namespace boot {
        namespace CD {
            using JabyEngine::CD::internal::Command;

            void setup() {
                static constexpr auto DebugX     = 1;
                static constexpr auto DebugY     = 1;
                static constexpr auto DebugScale = 1.0;

                __debug_boot_color_at(::JabyEngine::GPU::Color24::White(), DebugX, DebugY, DebugScale);
                SysCall::EnterCriticalSection();
                    Memory_IO::COM_DELAY.write(Memory_IO_Values::COM_DELAY::create());
                    Memory_IO::CD_DELAY.write(Memory_IO_Values::CD_DELAY::create());

                    SysCall::SysEnqIntRP(SysCall::Priority::CdromIoIrq, &::JabyEngine::CD::internal::irq_callback);

                    CD_IO::PortIndex1::change_to(); 
                    CD_IO::Interrupt::ack_extended(CD_IO::PortIndex1::InterruptFlag); 

                    // TODO: Verify this on real HW
                    CD_IO::Interrupt::enable_extended(CD_IO::PortIndex1::InterruptEnable); 

                    Interrupt::enable_irq(Interrupt::CDROM);
                    Interrupt::ack_irq(Interrupt::CDROM);
                SysCall::ExitCriticalSection(); 
            }
        }
    }
}