(ns com.oly.static-sites.do-blog.pages.chess.render
  (:require
   [com.oly.static-sites.do-blog.pages.chess.board
    :refer [calculate-black-white create-board-data-map]]
   [com.oly.static-sites.do-blog.pages.chess.movement
    :refer [fetch-selected-piece-moves]]
   [com.oly.static-sites.do-blog.pages.chess.state
    :refer
    [black-square game-state white-square]]))

(defn draw-square [pos pieces]
  (let [square (calculate-black-white pos)
        piece (first (filter #(= pos (:start-pos %)) pieces))
        selected-piece-moveable (fetch-selected-piece-moves (first (filter :selected pieces)) @game-state)
        moveable-square (first (filter #(= pos %) selected-piece-moveable))]

    (-> piece (assoc :text (cond
                             (:selected piece) (:character piece) ;"S "
                             piece (:character piece)
                             moveable-square "O "
                             :else (if (= (calculate-black-white pos) :black)
                                     black-square
                                     white-square)))
        (assoc :colour (if (= square :black)
                         white-square
                         black-square)
               :class (if (= square :black)
                        "black-80"
                        "white-80")))))

(defn create-board [size square-defaults]
  (create-board-data-map size square-defaults))

(defn enhance-board [board on-click-fn]
  (reduce-kv
   (fn [m key square]
     (assoc m key (assoc square :on-click on-click-fn :pos key)))
   {}
   board))

(defn place-pieces-on-board [board pieces on-click-fn]
  (reduce (fn [m piece]
            (let [square-colour (calculate-black-white (:start-pos piece))]
              (assoc m (:start-pos piece)
                     (merge (get m (:start-pos piece))
                            {:text (:character piece)
                             :piece (assoc piece :pos (:start-pos piece))
                             :selected false
                             :colour (:colour piece)
                             :on-click on-click-fn
                             :class (if (= square-colour :white)
                                      (str (if (= :white (:colour piece))
                                             " white "
                                             " black "))

                                      (str (if (= :white (:colour piece)) " white " " black")))}))))
          board
          pieces))


(comment (create-board 5))
