(ns buddho.core.pixi
  (:require ["pixi.js" :as PIXI]
            [buddho.core.state :as s]))

(defn describe-properties! []
  (s/describe-property! [:canvas] "PixiJS Canvas object.")
  (s/describe-property! [:canvas :main] "Main PixiJS canvas")
  (s/describe-property! [:pixi] "PixiJS object.")
  (s/describe-property! [:pixi :container] "PixiJS container object.")
  (s/describe-property! [:world] "PixiJS world container."))

(defn make-canvas! [width height]
  (let [canvas (PIXI/Application. #js {:width width :height height
                          :backgroundColor 0x444444})
        world (PIXI/Container.)
        [cid wid] (s/have-idea! "pixi_cont_" 2)]
    (s/update-idea! cid {:object canvas})
    (s/register-property! cid [:canvas :main] [:pixi :container])

    (s/update-idea! wid {:object world})
    (s/register-property! wid [:world] [:pixi :container])

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

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

(defn clear-canvas! []
  (let [cur-canvas (.querySelector js/document.body ".game-view")
        canvas-idea (first (s/with-property [:canvas :main]))]
    (when cur-canvas
      (.removeChild js/document.body cur-canvas))
    (when canvas-idea
      (s/forget-idea! canvas-idea))))

(defn make-sprite! [url]
  (-> PIXI .-Sprite (.from url)))

(defn world []
  (-> (s/with-property [:world])
        first
        s/value
        :object))

(defn add-sprite! [sprite]
  (.addChild ^js/PIXI.Container (world) sprite))
