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

    (map (partial polar-point r) (range 0.0 (* 2 Math/PI) step))))

(defn- test-sequence
  [{:keys [precision max-font-size max-test-radius] :as args}]
  (let [imprecision (* (- 1.0 precision) (- 1.0 precision))
        radii (take-while
                  #(< % max-test-radius)
                  (map #(* (+ 1 (* imprecision max-font-size)) %) (lazy-numbers 1)))
        rings (map #(test-ring % precision) radii)]
    (cons (point) (apply concat rings))))

(defn- check-position
  [test-area boundaries {:keys [rect]} p]
  (let [rect* (translate-rect rect p)]
  (and
   (.contains boundaries rect*)
   (not (.intersects test-area rect*)))))

(defn- find-position
  [test-area boundaries point-sequence {:keys [rect] :as word-info}]
  (first (filter #(check-position test-area boundaries word-info %)
              point-sequence)))

(defn generate-cloud
  [word-infos & args]

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

(defn- cloud-painter
  [{:keys [word-infos test-area]} g w h]
  (let [c (point (/ w 2.0) (/ h 2.0))
        bg (translate-area test-area c)]
    (doto g
      setup
      ;(draw-rect (rectangle 0 0 (dec w) (dec h)))
      ;(fill-shape bg)
      ;(draw-shape bg)
      )
    (doseq [{:keys [text font position rotation]} (filter #(not (nil? %)) word-infos)]
      (draw-string-centered g text (translate-point c position) :font font :rotation rotation))))

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

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

