(ns advent.utils
  (:require [play-clj.core :refer :all]
            [play-clj.ui :refer :all]
            [play-clj.utils :refer :all]
            [play-clj.g2d :refer :all]
            [clojure.edn :as edn])
  (:import [com.badlogic.gdx.graphics Pixmap Pixmap$Filter Texture Texture$TextureFilter]
           [com.badlogic.gdx.graphics.g2d TextureRegion]
           [java.lang Object]))

(defn log-coords [screen entities]
  (let [{:keys [x y]} (input->screen screen {:x (:input-x screen) :y (:input-y screen)})]
    (println (:input-x screen) (:input-y screen) "->" x y)))

(def +all-cursors+ [:main :wool :mushrooms :carrot :right :down :left :up :flask :flask-with-contents :trophy :ladder :stick :cat-toy :balloon :frog-legs :teddy :portrait :recipe :glass-eye :motivational-tapes :used-earplugs :grass :slobber :flask-with-strength :medal :certificate])

(defn cursor [filename which]
  (let [scale 2
        base-cursor (pixmap filename)
        target-width (* 16 scale)
        target-height (* 16 scale)
        resized (Pixmap. target-width target-height (.getFormat base-cursor))
        index (.indexOf +all-cursors+ which)]
    (Pixmap/setFilter Pixmap$Filter/NearestNeighbour)
    (pixmap! resized :draw-pixmap base-cursor (* index 16) 0 16 16
             0 0 target-width target-height)
    resized ))

(defn save [entities]
  (spit "save.edn" (entities :state)))

(defn load []
  (edn/read-string (slurp "save.edn")))

(defn get-font [filename]
  (let [font (bitmap-font filename) 
        tr (bitmap-font! font :get-region)
        tx (.getTexture tr)]
    (texture! tx :set-filter Texture$TextureFilter/Linear Texture$TextureFilter/Linear)
    font))

(def +screen-width+ 320)
(def +screen-height+ 240)

(defn scaler-fn-with-baseline [baseline minimum-size & [maximum-size]]
  (let [maximum-size (or maximum-size 1.0)]
    (fn [[_ y]]
      (if (< y baseline) maximum-size
          (let [percent-complete (- 1.0 (/ (- y baseline) (- +screen-height+ baseline)))
                range (+ (* percent-complete (- maximum-size minimum-size)) minimum-size)]
            range)))))

(defn scaler-fn-from-image [image minimum-size maximum-size]
  (let [image (pixmap image)
        maximum-size (or maximum-size 1.0)]
    (fn [[x y]]
      (let [percent-complete (-> image
                                 (pixmap! :get-pixel x (- 240 y))
                                 color
                                 (.r))]
        (+ (* percent-complete (- maximum-size minimum-size)) minimum-size)))))

(defn dist [x1 y1 x2 y2]
  (let [dx (- x1 x2)
        dy (- y1 y2)]
    (Math/sqrt (+ (* dx dx) (* dy dy)))))


(defn flip [anim]
  (animation (animation! anim :get-frame-duration)
             (for [src-frame (animation! anim :get-key-frames)
                   :let [frame (texture (texture! src-frame :get-texture))]]
               (do
                 (texture! frame :set-region src-frame)
                 (texture! frame :flip true false)
                 frame))))
