(ns anime.mass3
  (:import (java.awt Dimension Color)
           (javax.swing JFrame JPanel)))

(require 'src.math)
(alias 'mt 'src.math)

(defn phys [[theta0 theta1 theta0-dot theta1-dot]]
  [theta0-dot
   theta1-dot
   0.0
   0.0])

(def xi (ref [0.0 0.0 1.0 1.66]))

(defn irredundant-to-cartesian [[theta0 theta1 _ _]]
  [(* 0.5
      (Math/sin theta0))
   (* 0.5
      (- (Math/cos theta0)))

   (* 0.5
      (+ (Math/sin theta0)
         (Math/sin theta1)))
   (* 0.5
      (- 0.0
         (Math/cos theta0)
         (Math/cos theta1)
         ))])

(defn coord-real-to-display [[x y]]
  [(+ 120 (* x 100))
   (+ 120 (* y -100))])

(defn anime-panel []
  (proxy [JPanel] []
    (paintComponent [g]
      (proxy-super paintComponent g)
      (.setColor g Color/BLUE)
      (let [[x0 y0 x1 y1] (irredundant-to-cartesian @xi)
            [disp0x disp0y] (coord-real-to-display [0 0])
            [x0 y0] (coord-real-to-display [x0 y0])
            [x1 y1] (coord-real-to-display [x1 y1])]
        (.fillOval g (- x0 5) (- y0 5) 11 11)
        (.fillOval g (- x1 5) (- y1 5) 11 11)
        (.drawLine g disp0x disp0y x0 y0)
        (.drawLine g x0 y0 x1 y1)
        ))
    (getPreferredSize []
      (Dimension. 240 240)
      )))

(defn make-panel []
  (let [frame (JFrame. "mass3")
        panel (anime-panel)]
    (doto frame
      (.add panel)
      (.pack)
      (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE)
      (.setVisible true))
    panel))

(let [panel (make-panel)]
  (loop [i 0]
    (if (>= i 2000)
      true
      (do
        (dosync
          (let [tmp (mt/eular-implicit phys @xi 0.02 0.01)
                to-0-2pi (fn [x] (if (>= x (* 2 Math/PI))
                                   (- x (* 2 Math/PI))
                                   x))
                tmp (mt/tfassoc tmp [0] to-0-2pi)
                tmp (mt/tfassoc tmp [1] to-0-2pi)]
            (ref-set xi tmp)
            (println @xi)
            (.repaint panel)))
        (recur (inc i))
        ))))
