(define-module (game render level)
  #:use-module (game model level)
  #:use-module (game util assets)
  #:use-module (srfi srfi-64)
  #:use-module (chickadee graphics color)
  #:use-module (chickadee graphics sprite)
  #:use-module (chickadee graphics texture)
  #:use-module (chickadee graphics text)
  #:use-module (chickadee math vector)
  #:export (render-level-load
            render-level-draw
            render-level-set!
            render-victory
            ))


(define sprite-batch #f)

;; load the tile texture and split it into a tile atlas
(define (render-level-load)
  (set! sprite-batch (make-sprite-batch tile-texture #:capacity 1200))
  )



;; map tile symbols to tile indices in the tile atlas
(define (level-tile-index tile)
  (case tile
    ((empty) 3800)
    ((brick) 3750)
    ((wall) 3709)
    ((ladder) 3350)
    ((goal) 3800)           ;; render empty tile for goal location
    ((hero) 3800)          ;; render empty tile for hero start location
    ((other) 3800)           ;; render empty tile for enemy start location
    ((key) 3800)
    ;; render visual reminder of unknown tile
    (else 3326)))


;; update the sprite-batch for the passed level
(define (render-level-set! level)
  (sprite-batch-clear! sprite-batch)
  (for-each 
   (lambda (row)
     (for-each
      (lambda (column)
        (let* 
            ((position (vec2 (* 16 column) (* 16 row)))
             (tile (level-tile-at level position))
             (texture-region (texture-atlas-ref tile-atlas (level-tile-index tile))))
          (sprite-batch-add! sprite-batch position 
                             #:texture-region texture-region)))
      (iota (level-width level) 0)))
   (iota (level-height level) 0)))

;; render the level tiles
(define (render-level-draw level)
  (draw-sprite-batch sprite-batch))


(define (render-victory)
  (draw-sprite (load-image (assets-file-name "assets/images/victory.jpg")) (vec2 0 0)))

(test-begin "tile translation")

(test-equal (level-tile-index 'empty) 3800)
(test-equal (level-tile-index 'brick) 3750)
(test-equal (level-tile-index 'wall) 3709)
(test-equal (level-tile-index 'ladder) 3350)
(test-equal (level-tile-index 'goal) 3404)
(test-equal (level-tile-index 'unknown) 3326)

(test-end "tile translation")
