(ns buddho.core.graphics
  (:require [buddho.core.pixi :as pixi]
            [buddho.core.state :as s]))


(defn clear-canvas! []
  (pixi/clear-canvas!))

(defn make-sprite! [url]
  (pixi/make-sprite! url))

(defn world [] (pixi/world))

(defn add-sprite! [sprite] (pixi/add-sprite! sprite))

(defn screen-meta [] (s/singleton-value [:meta :screen]))
(defn set-screen-meta! [width height]
  (s/set-singleton! [:meta :screen] {:width width :height height}))

(defn render-meta [] (s/singleton-value [:meta :render]))
(defn set-render-meta! [tile-size]
  (s/set-singleton! [:meta :render] {:tile-size tile-size}))


(defn make-canvas! [& [width height]]
  (let [screen (screen-meta)
        width (or width (:width screen))
        height (or height (:height screen))]
    (pixi/make-canvas! width height)))

(defn screen-center []
  (let [screen (screen-meta)]
    {:x (-> screen :width (/ 2))
     :y (-> screen :height (/ 2))}))

(defn camera [] (s/singleton-value [:meta :camera]))
(defn set-camera! [x y]
  (s/set-singleton! [:meta :camera] {:x x :y y}))

(defn translate-screen [{sx :x sy :y} {bx :x by :y bz :z}]
  (let [tile (:tile-size (s/singleton-value [:meta :render]))
        halftile (/ tile 2)
        trans-x (map #(* bx %) [tile (- halftile)])
        trans-y (map #(* by %) [(- tile) (- halftile)])
        trans-z (map #(* bz %) [0 tile])
        trans [[sx sy] trans-x trans-y trans-z]]
    {:x (apply + (map first trans))
     :y (apply + (map second trans))}))

(defn world->screen [{:keys [x y z]}]
 (translate-screen (camera) {:x (- x) :y (- y) :z (- z)}))
