(module (bd music) *
(import scheme
	(chicken base)
	(chicken module)
	(chicken foreign)
	raylib
	(imugi core)
	foreigners
	(srfi 69)
	(srfi 99))

(foreign-declare "#include <raylib.h>")

(define-foreign-record-type (Music "struct Music")
  (constructor: make-music)
  (destructor: free-music))

(define load-music-stream
  (foreign-lambda* Music ((c-string filepath))
    "
Music * music = malloc(sizeof(Music));
*music = LoadMusicStream(filepath);
C_return(music);"))

(define unload-music-stream
  (foreign-lambda* void ((Music music))
    "
UnloadMusicStream(*music);
"))

(define play-music-stream
  (foreign-lambda* void ((Music music))
    "
PlayMusicStream(*music);
"))

(define update-music-stream
  (foreign-lambda* void ((Music music))
    "
UpdateMusicStream(*music);
"))

(define stop-music-stream
  (foreign-lambda* void ((Music music))
    "
StopMusicStream(*music);
"))

(define set-music-volume
  (foreign-lambda* void ((Music music) (float volume))
    "
SetMusicVolume(*music, volume);
"))

(define current-music #f)
(define current-music-path "")

(define-record-type <music-player>
  (music-player path)
  music-player?
  (path music-player-path))

(define handle-music-players
  (make-system
   'handle-music-players
   0
   'entity
   '(<music-player>)
   (lambda (_ player)
     (if (not (equal? current-music-path (music-player-path player)))
	 (begin (when current-music
		  (unload-music-stream current-music))
		(set! current-music (load-music-stream (music-player-path player)))
		(set! current-music-path (music-player-path player))
		(play-music-stream current-music))
	 (update-music-stream current-music)))))
)
