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

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

(defn L [[t [x y] [vx vy]]]
  (let [k 10 m 0.1]
    (- (* 0.5 m
          (+ (* vx vx) (* vy vy))
          )
       (* 0.5 k
          (let [d (Math/sqrt (+ (* x x) (* y y)))]
            (* (- d 0.5) (- d 0.5))
            )))))

(def A (mt/L->accer 0.02 0.01 0.01 L (fn [_] 0)))

(defn phys [xi]
  (let [n (/ (count xi) 2)
        q (take n xi)
        qdot (drop n xi)
        qddot (A [0 q qdot])]
    (concat qdot qddot)))

(def xi (ref [1 0 0 -1]))

(defn anime-panel []
  (proxy [JPanel] []
    (paintComponent [g]
      (proxy-super paintComponent g)
      (.setColor g Color/BLUE)
      (let [x (+ 120 (* (nth @xi 0) 100))
            y (+ 120 (* (nth @xi 1) -100))]
        (.fillOval g (- x 5) (- y 5) 10 10)))
    (getPreferredSize []
      (Dimension. 240 240)
      )))

(defn make-panel []
  (let [frame (JFrame. "mass1")
        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 1000)
      true
      (do
        (dosync
          (ref-set xi (mt/eular-implicit phys @xi 0.02 0.01))
          (println @xi)
          (.repaint panel))
        (recur (inc i))
        ))))
