 (ns notifier.core
-  (:import [javax.crypto Mac]
-           [javax.crypto.spec SecretKeySpec]
-           [java.util Base64])
-  (:require [clojure.data.json :as json]
-            [clj-time.core :as t]
-            [chime :refer [chime-at]]
-            [clj-time.periodic :refer [periodic-seq]]
+  (:gen-class)
+  (:require [chime :refer [chime-at]]
+            [clj-time
+             [core :as t]
+             [periodic :refer [periodic-seq]]]
+            [clojure.data.json :as json]
+            [clojure.edn :as edn]
             [org.httpkit.client :as http])
-  (:gen-class))
+  (:import [java.io FileReader PushbackReader]
+           java.util.Base64
+           javax.crypto.Mac
+           javax.crypto.spec.SecretKeySpec))
 
 ;; ASX-ordinaries http://www.marketindex.com.au/all-ordinaries
 

            (swap! last-prices assoc c price)))))))

(defn schedule []
  (let [notifier (mk-price-nofifier [5 10 20 30 40 50 100])
        times (periodic-seq (t/now) (-> 2 t/minutes))]
    (chime-at times (fn[time]
                      (println "chiming at " time)


(defn publish-event [level price percent]
  (let[url (format  "https://maker.ifttt.com/trigger/BTC-AUD-%s/with/key/%s" level @ifttt-key)
       {:keys[status body]} @(http/post url {:headers {"Content-Type" "application/json"}
                                            :body (json/write-str {:value1 (str price)
                                                                   :value2 (str percent)})})]
    (println "published event:" url " result:" status ":" body)
    status))

(defn persistent-atom [file initial]
  (let[data (atom (try
                    (-> file (FileReader.) (PushbackReader.) (edn/read))
                    (catch Exception e
                      (println "failed reading file " file ":" e)
                      initial)))]
    (add-watch data
               (fn[k r o n]
                 (spit file (pr-str n))))
    data))

(defn mk-price-nofifier [changes file]
  (let[last-prices (persistent-atom file)]
    (fn[]
      (if-let [price (get-btc-price)]
        (doseq [c changes :let [last-price (@last-prices c)]]
