 (ns ccw.repl.cmdhistory
   (:use (clojure.contrib def core))
   (:import
+    ccw.CCWPlugin
     org.eclipse.core.runtime.jobs.Job
-    org.eclipse.core.runtime.IProgressMonitor))
+    org.eclipse.core.resources.IResource
+    org.eclipse.core.runtime.IProgressMonitor
+    org.osgi.service.prefs.BackingStoreException
+    org.eclipse.core.runtime.preferences.IEclipsePreferences))
 
 (defvar- queued-commands (ref {})
   "Map between project names and vectors of REPL expressions that have yet to

       (partial queue-expression project-name)]
      [[] identity])))

(defn- save-history
  [project-name history]
  (doto (get-pref-node project-name)
    (.put history-key (pr-str history))
    .flush))

(defvar- save-cmds-job
  (doto (proxy [Job] ["ccw REPL command history persistence"]
          (run [^IProgressMonitor pm]
            (.beginTask pm "Persisting REPL histories" IProgressMonitor/UNKNOWN)
            (doseq [[project-name exprs] (dosync (let [queued @queued-commands]
                                                  (ref-set queued-commands {})
                                                  queued))
                    :let [[history] (get-history project-name)]]
              (.subTask pm project-name)
              (save-history project-name (->> (reverse exprs)
                                           (concat history)
                                           (take-last max-history)
                                           ; prevent consecutive duplicate expressions
                                           (partition-by identity)
                                           (mapcat (partial take 1))
                                           vec)))
            (.done pm)
            (.schedule this persist-schedule-ms)
            org.eclipse.core.runtime.Status/OK_STATUS))
    (.setSystem true)))

(defn- schedule-job

(defvar- persist-schedule-ms 30000
  "Queued commands are persisted to project preferences every _ milliseconds.")

(defn- ^IEclipsePreferences get-pref-node
  [project-name]
  (-?> project-name
    ccw.launching.LaunchUtils/getProject
    org.eclipse.core.resources.ProjectScope.
    (.getNode pref-node-id)
    (doto .sync))) 

(defn- queue-expression
  [project-name expr]
