(ns frontend.il.app
  (:require ["pixi.js" :as pixi]
            [goog.dom :as dom]))

(def websocket (doto (js/WebSocket. (str "ws://" js/location.host "/ws"))
                 (.addEventListener "open" #(println "Websocket opened."))
                 (.addEventListener "message" #(println "Received message:" (.-data %)))
                 (.addEventListener "close" #(println "Websocket closed."))))

(defn ticker [game ticker-object]
  (let [bunny (game :bunny)]
    (set! (.-rotation bunny) (+ (.-rotation bunny) 0.01))))

(defn init []
  (let [app (pixi/Application.)
        width (.-width js/window.screen)
        height (.-height js/window.screen)]
    (.. app
        (init #js {:width width :height height :backgroundColor 0x1099bb})
        (then (fn [_]
                (dom/appendChild (dom/getElement "app") (.-canvas app))
                (let [texture (.. pixi -Assets (load "https://www.sprite-ai.art/sprite-img/99fa1574-fc52-41a6-ab76-1bd75b5dc4b3/16x16-pixel-art-sprite-cookie-shaped-like-a-32x32-pixel-art-90b4.png"))]
                  (.. texture
                      (then (fn [loaded-texture]
                              (let [bunny (pixi/Sprite. loaded-texture)]
                                (set! (.. bunny -anchor -x) 0.5)
                                (set! (.. bunny -anchor -y) 0.5)
                                (set! (.. bunny -x) (/ width 2))
                                (set! (.. bunny -y) (/ height 2))
                                (.. app -stage (addChild bunny))
                                (.. app -ticker (add (partial ticker {:bunny bunny})))))))))))))
