(ns sekai.core.init
  (:require ["pixi.js" :as PIXI]
            [sekai.core.gamestate :as gs :refer [game-state]]
            [sekai.io.pixi :as pixi]
            [sekai.core.logging :refer [log]]
            [sekai.entity.component :as comp]
            [sekai.entity.entity :as entity]
            [sekai.io.display :as render]
            [sekai.core.space :as space]))

(defn init []
  ;;; reset game state
  (gs/reset-game-state!)

  (let [canvas (pixi/make-canvas! 512 512)
        bunny (entity/register-entity! "bunny")
        world (PIXI/Container.)]

    ;;; remove old view
    (when-let [old-view
               (-> "game-view"
                   js/document.getElementsByClassName
                   (.item 0))]
      (.remove old-view))

    ;;; Add canvas and world container
    (swap! game-state update-in [:canvas] assoc :canvas canvas)
    (swap! game-state update-in [:canvas] assoc :world world)

    (.appendChild js/document.body (.-view canvas))
    (.addChild (.-stage canvas) world)
    (set! (.-className (.-view canvas)) "game-view")

    ;;; Scaling
    (set! (.-SCALE_MODE (.-settings PIXI)) (.-NEAREST (.-SCALE_MODES PIXI)))
    (.set (-> canvas .-stage .-scale) 2)

    (doseq [x (range -12 12)
            y (range -12 12)
            z (range -3 0)]
      (let [eid (entity/register-entity! (str "block[" x "," y "].e"))
            color (nth '("" "_red" "_green")
                       (mod y 3))]

          (comp/attach!
           (comp/position x y z)
           eid)

          (comp/attach!
           (comp/sprite (str "/assets/prart_tile_square_32x32" color ".png"))
           eid)))

    (comp/attach!
     (comp/position 0 0 -4)
     bunny)

    (comp/attach!
     (comp/sprite "https://pixijs.com/assets/bunny.png")
     bunny)

    (let [ticker (.-ticker canvas)]
      (.remove ticker render/render!)
      (.add ticker render/render!))

    (println canvas)))
