#include "../../internal-include/CD/cd_internal.hpp"
#include <PSX/Audio/CDDA.hpp>

namespace JabyEngine {
    namespace CDDA {
        namespace CD = JabyEngine::CD::internal;

        static CD::BCDTimeStamp last_track;
               CD::BCDTimeStamp playing_track;

        TrackList get_tracks() {
            CD::Command::send_wait_response(CD_IO::Command::GetTN);
            
            const auto stat       = CD_IO::PortIndex0::ResponseFifo.read();
            const auto first      = CD_IO::PortIndex0::ResponseFifo.read().raw;
            const auto end        = CD_IO::PortIndex0::ResponseFifo.read().raw;
            const auto last_track = (end - first) + 1;

            if(last_track == 1) {
                return TrackList::empty();
            }

            return TrackList{.first_track = 2, .last_track = static_cast<uint8_t>(last_track)};
        }

        void play(uint8_t track) {
            CD::enable_CDDA(); 
            CD::Command::send_wait_response(CD_IO::Command::GetTD, track);
            const auto stats  = CD_IO::PortIndex0::ResponseFifo.read().raw;
            playing_track.min = CD_IO::PortIndex0::ResponseFifo.read().raw;
            playing_track.sec = CD_IO::PortIndex0::ResponseFifo.read().raw;

            CD::Command::send(CD_IO::Command::SetLoc, playing_track.min, playing_track.sec, 0x0_u8);
            CD::Command::send(CD_IO::Command::Play);
            // The PS3 does not support playing a track by track id
            //CD::Command::send(CD_IO::Command::Play, track);
        }

        void stop() {
            CD::pause();
        }

        void push_play() {
            stop();
            last_track = CD::get_loc();
        }

        void pop_play() {
            CD::enable_CDDA(); 
            CD::Command::send(CD_IO::Command::SetLoc, last_track.min, last_track.sec, last_track.sector);
            CD::Command::send(CD_IO::Command::Play);
        }
    }
}