; SPDX-FileCopyrightText: 2023 Jummit
;
; SPDX-License-Identifier: GPL-3.0-or-later

(local {:icons card-icons} (require :cards))

(fn arrange-on-circuit-mat [entities]
  (each [_ entity (ipairs entities)]
    (case entity
      {:circuit-x x :circuit-y y}
      (do
        (set entity.x (+ (* x 16) 40 (if entity.card 3 0)))
        (set entity.y (+ (* y 16) -27))))))

(fn draw-cells [entities]
  (each [_ entity (ipairs entities)]
    (case entity
      {:cell {:core true}}
      nil
      {:cell {:exit-for 1} : x : y}
      (do
        (_G.spr 270 x (+ y 7) 0 1 2 0 2 2)
        (_G.spr 300 x (- y 1) 0 1 0 0 2 1))
      {:cell {:exit-for 2} : x : y}
      (do
        (_G.spr 270 x (- y 9) 0 1 0 0 2 2)
        (_G.spr 302 x (+ y 7) 0 1 0 0 2 1))
      {:cell {:fire-walled by} : x : y}
      (_G.rect x (- y 1) 16 16 (. [4 9] by))
      (where {: x : y} entity.cell)
      (_G.spr 268 x (- y 1) 0 1 0 0 2 2))))

(fn draw-highlighted-cells [world]
  (each [_ entity (ipairs world)]
    (case entity
      {:highlighted-cell true : x : y :selected true}
      (_G.spr 330 x (- y 1) 6 1 0 0 2 2)
      {:highlighted-cell true : x : y}
      (_G.spr 298 x (- y 1) 6 1 0 0 2 2))))

(fn draw-slots [entities]
  (each [_ entity (ipairs entities)]
    (case entity
      {:slot {: kind :border ?border} : x : y}
      (do
        (_G.rect (+ x 1) y 9 12 14)
        (_G.spr (if ?border 296 262) x y 6 1 0 0 2 2)
        (_G.spr (. card-icons kind) (+ x 2) (+ y 2) 6)))))

(fn arrange-in-slots [world]
  (each [_ entity (ipairs world)]
    (case entity
      {:in-slot {: x : y}}
      (do
        (set entity.x x)
        (set entity.y y)))))

(fn draw-game-over [world]
  (case world.phase
    {:kind :game-over : won}
    (let [y (* (math.sin (/ (_G.time) 500)) 2)]
      (_G.rect 0 40 300 50 15)
      (print "GAME OVER" 60 (+ y 50) 13 false 2)
      (let [msg (if (= won :player) "You won!" "You lost!")]
        (print msg 70 (+ y 70) 13 false 2)))))

(fn draw-speech-bubbles [world]
  (each [_ entity (ipairs world)]
    (case entity
      {:speech-bubble {: text :progress progress? &as bubble} : x : y}
      (let [progress (or progress? 0)]
        (_G.map 12 17 11 5 x y 0)
        (_G.print (text:sub 1 (math.ceil progress)) (+ x 2) (+ y 11) 0 false 1
                  true)
        (set bubble.progress (+ progress 0.3))))))

{: arrange-on-circuit-mat
 : draw-cells
 : draw-highlighted-cells
 : draw-slots
 : draw-game-over
 : arrange-in-slots
 : draw-speech-bubbles}