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

;; Build the entities for a match.

(local {: terminals} (require :cards))
(local circuit-mat-layout [:xxxccxxx
                           :YYYbbYYY
                           :CCCYYCCC
                           :CCCCCCCC
                           :CCCCCCCC
                           :CCCCCCCC
                           :CCCCCCCC
                           :CCCBBCCC
                           :BBByyBBB
                           :xxxccxxx])

(fn make-circuit-mat [entities]
  (each [y line (ipairs circuit-mat-layout)]
    (for [x 1 (length line)]
      (let [kind (line:sub x x)]
        (when (not= kind :x)
          (local cell {})
          (case kind
            :Y
            (set cell.start-for 1)
            :y
            (set cell.exit-for 1)
            :B
            (set cell.start-for 2)
            :b
            (set cell.exit-for 2)
            :c
            (set cell.core true))
          (table.insert entities {:circuit-x x :circuit-y y : cell}))))))

(fn make-slots [entities]
  (for [i 1 4]
    (let [x (+ (* i 12) -12)
          right-x (+ x 190)
          y 3
          down-y 120]
      (table.insert entities {:slot {:kind :virus :owner 1} : x : y})
      (table.insert entities {:slot {:kind :virus :owner 2} : x :y down-y})
      (table.insert entities {:slot {:kind :link :owner 1} :x right-x : y})
      (table.insert entities {:slot {:kind :link :owner 2}
                              :x right-x
                              :y down-y})
      (let [yellow-slot {:slot {:kind (. terminals i) :owner 1 :used true}
                         : x
                         :y 20}
            blue-slot {:slot {:kind (. terminals i) :owner 2 :used true}
                       : x
                       :y 103}]
        (table.insert entities yellow-slot)
        (table.insert entities blue-slot)
        (table.insert entities
                      {:in-slot yellow-slot
                       :card {:owner 1 :kind yellow-slot.slot.kind :open true}})
        (table.insert entities
                      {:in-slot blue-slot
                       :card {:owner 2 :kind blue-slot.slot.kind :open true}})))))

(fn make-decks [entities]
  (each [_ kind (ipairs [:link :virus])]
    (for [_ 1 4]
      (for [owner 1 2]
        (table.insert entities
                      {:card {: owner : kind} :x 20 :y (- (* owner 48) 10)})))))

{: make-circuit-mat : make-slots : make-decks}