(eval-when (:compile-toplevel :load-toplevel :execute)
  (unless (find-package "CLIM-USER")
    (ql:quickload "mcclim")))

(in-package "CLIM-USER")

(defparameter *example* (clim:open-window-stream :background +black+
                                           :width 1280 :height 720
                                           :scroll-bars NIL))

(defun draw-dots (stream)
  (window-clear stream)
  (loop repeat 32
        for x = (random 1280)
        for y = (random 720)
        do (draw-circle* stream x y 25 :ink +white+))
  (finish-output stream))

(draw-dots *example*)

(defclass adversarial-bubble ()
  ((phase :initform 0)
   (ink :initform +red+ :initarg :ink)
   (state :initform :stopped)))

(defun start-adversarial-bubble (stream ink rad dir)
  (let ((bubble (make-instance 'adversarial-bubble :ink ink)))
    (clim-sys:make-process
     (lambda ()
       (with-slots (phase ink state) bubble
         (setf state :running)
         (loop while (eql state :running) do
           (let ((x (+ (* dir (sin phase) rad) 640))
                 (y (+ (* (cos phase) (* rad 9/16)) 360)))
             (updating-output (stream :unique-id bubble)
               (draw-circle* stream x y 10 :ink ink))
             (incf phase 1/60)
             (finish-output stream)
             (sleep 1/60)))
         (setf state :stopped))))
    bubble))

(defun stop-adversarial-bubble (bubble)
  (setf (slot-value bubble 'state) :done))

(defparameter *bubble* (make-instance 'adversarial-bubble))

(dotimes (v 8)
  (start-adversarial-bubble *example* (if (evenp v) +red+ +blue+) 600 1)
  (start-adversarial-bubble *example* (if (evenp v) +green+ +yellow+) 300 -1)
  (sleep 1))
;(stop-adversarial-bubble *bubble*)

