 (defonce output (async/chan))
 (defonce exception (async/chan))
 
-(defn js-handle [fn]
-  (println "executing stuff in " (Thread/currentThread))
-  (fn))
+(defn- js-handle [fn] (fn))
 
-(defn js-loop []
+(defn- js-loop []
   (async/thread (while true
                   (let [fn (async/<!! input)]
                     (try

  (eval-str "function parseFont(payload) { return opentype.parse(b64.decode(payload)); }")
  (swap! parsefont (fn [old-parsefont] (.get @scope "parseFont"))))

(defn bootstrap-rhino-if-needed []
  (when-not @cx (run-js-thread bootstrap-rhino)))

(defn load-font [filename]
  (if-not (get @fonts filename)
    (let [font-bytes (FileUtils/readFileToByteArray (File. filename))
          font-b64 (String. (base64/encode-bytes font-bytes))]
      (run-js-thread (fn []
                       (swap! fonts (fn [old-fonts]
                                      (println "loading font" filename)
                                      (assoc old-fonts filename (.call @parsefont @cx @scope @scope (object-array [font-b64])))))))
      :done)
    :already-loaded))

(defn load-fonts []
  (bootstrap-rhino-if-needed)
  (doall (map load-font ["./resources/fonts/Roboto-Black.ttf"
                         "./resources/fonts/Roboto-Regular.ttf"])))

;
;(defn js-to-clj [x]
;  (zipmap (map keyword (keys x)) (vals x)))
;
;

#_(defn get-path
    [text size]

                        (println "error in js-loop ..." (.getMessage e))
                        (async/>!! exception e)))))))

(defn- run-js-thread [f]
  (async/>!! input f)
  (let [[result ch] (async/alts!! [output exception])]
    (if (= ch exception)
      (throw result)
      result)))

(defonce js-loop-thread (js-loop)) ;;; bootstrap JS loop

;;; ;;; ;;; STATE
(defonce cx (atom nil))
