 (ns mastersign.wordcloud
-  (:import [java.lang Math])
   (:import [java.awt Graphics Graphics2D Color RenderingHints Font])
   (:import [java.awt.geom Area
             Rectangle2D Rectangle2D$Float

        {:keys [width height padding]} args
        boundaries (area (rectangle (- (/ width 2)) (- (/ height 2)) width height))
        *test-area* (area)
        point-sequence (test-sequence args)
        finder (fn [{:keys [text rect] :as word-info}]
                 ;(println (str "Placing " text " ..."))
                 (let [hit (find-position *test-area* boundaries point-sequence word-info)]
                   (if (nil? hit)
                     nil
                     (do
                       (.add *test-area* (area (grow-rect (translate-rect rect hit) padding)))
                       ;(println (str "Found place at " (.x hit) ", " (.y hit)))
                       (assoc word-info :position hit)))))]
    (doall (map finder word-infos))))

(defn- cloud-painter
  [word-infos g w h]
  (doto g
    setup)

  (doseq [{:keys [text font position]} (filter #(not (nil? %)) word-infos)]
    (draw-string-centered g text
                          (+ (/ w 2.0) (.x position))
                          (+ (/ h 2.0) (.y position)) :font font)))

(defn paint-cloud
  [word-infos & args]
  (let [args (merge default-args)]
    (create-image (:width args) (:height args)
                  (partial cloud-painter word-infos))))

; ########################


(def base-font (Font. font-family font-style (float 100)))

(def default-args
  {:width 600
   :height 200
   :precision 0.5
   :font base-font
   :min-font-size 13
   :max-font-size 60
   :max-test-radius 350
   :padding 2
   :shape-mode :glyph-box ; :word-box, :glyph-box
   :allow-rotation true
   })

(defn- calc-font-size
  [{:keys [min-font-size max-font-size]} v]
  (float (+ min-font-size (* (- max-font-size min-font-size) v v))))

(defn- get-font
  [{:keys [font] :as args} v]
  (.deriveFont font (calc-font-size args v)))

(defn- build-word-info
  [g args [text value]]
  (let [font* (get-font args value)]
    {:text text
     :font font*
     :word-bounds (string-centered-bounds g font* text)
     :glyph-bounds (string-centered-glyphbounds g font* text)}))

(defn- build-word-infos
  [word-stats & args]
