 (ns metlog-client.metlog
   (:require-macros [cljs.core.async.macros :refer [ go ]]
                    [metlog-client.macros :refer [ watch ]])
-  (:require [reagent.core :as reagent :refer [atom]]
-            [ajax.core :refer [GET]]
+  (:require [reagent.core :as reagent]
+            [ajax.core :as ajax]
             [cljs.reader :as reader]
             [cljs.core.async :refer [put! close! chan <!]]
             [metlog-client.tsplot :as tsplot]))
 
-(defonce query-window-secs (atom (* 3600 24)))
+(defonce query-window-secs (reagent/atom (* 3600 24)))
 
-(def dashboard-state (atom {:series [] :text ""}))
+(def dashboard-state (reagent/atom {:series [] :text ""}))
 
-(def window-width (atom 1024))
+(def window-width (reagent/atom nil))
 
 (defn <<< [f & args]
   (let [c (chan)]

    c))

(defn ajax-get [ url callback ]
  (GET url {:handler callback
            :error-handler (fn [ resp ]
                             (.log js/console (str "HTTP error, url: " url " resp: " resp)))}))

(defn fetch-series-names [ cb ]
  (ajax-get "/series-names" cb))

(defn fetch-latest-series-data [ series-name cb ]
  (ajax-get (str "/latest/" series-name) cb))

(defn fetch-series-data [ series-name query-window-secs cb ]
  (ajax-get (str "/data/" series-name "?query-window-secs=" query-window-secs)
            (fn [ data ]
              (cb data))))

(defn tsplot-draw [ canvas width series-data ]
  (let [ ctx (.getContext canvas "2d")]
    (tsplot/draw ctx width 180 series-data)))

(defn dom-width [ node ]
  (if node
    (.-clientWidth node)
    1024))

(defn series-tsplot [ series ]
  (let [ series-state (atom { }) ]
    (reagent/create-class
     {:display-name (str "series-tsplot-" series)
      :component-did-update
      (fn [ this ]
        (tsplot-draw (reagent/dom-node this) (dom-width (:dom-node @series-state)) (:series-data @series-state)))
      
      :component-did-mount
      (fn [ this ]

    (reset! query-window-secs qws)))

(defn input-field [ on-enter ]
  (let [ state (reagent/atom { :text "" }) ]
    (fn []
      [:input {:value (:text @state)
               :onChange #(swap! state assoc :text (.. % -target -value))
