 (ns annual-weather.web-cache
-  (:import java.util.concurrent.TimeUnit)
+  (:import java.util.concurrent.TimeUnit
+           org.joda.time.DateTime)
   (:require 
     [annual-weather [cdo :as cdo]
                     [geocode :as geocode]]

  TODO log or store cache statistics !
  But this works !"
  [q :- s/Str] 
  (or (and read-db
           (some->> q
             (array-map :user-addr)
             (monger.collection/find-one-as-map "geocodeWebCache")
             :geocoded))
      (let [geocoded (if read-uc
                       (geocode/query-geocode-uncached q))]
        (pp/pprint geocoded)
        (if geocoded
          (do
            (if write-db (monger.collection/insert "geocodeWebCache"
              {:user-addr q
               :geocoded geocoded }))
            geocoded)))))

(sm/defn query-data-d3-style-uncached [q] :- cdo/D3-Schema
  (->> q
      (cdo/query :data) ; Ask for weather data
      unpack-http-kit-json-res ; parse the response
      :results
      cdo/group-results

                   [[(.getLeftLongitude extent) (.getMinLatitude extent)]
                    [(.getRightLongitude extent) (.getMaxLatitude extent)]] }}
                   :query-rest q-rest })
                 (map :station)
                 not-empty
                 (success-log "station"))))
        [q-date q-rest] (group-map-by-keys 
                          (dissoc q :limit :offset :sortorder :sortfield)
                          [:startdate :enddate])]
    (or (maybe-read-db q-rest extent)
        (if read-uc
          (if-let [stations (cdo/query-stations-uncached q (geocode/window-to-gmaps-url extent))]
              (do 
                (if log-caching
                  (info "read uc station data"))
                (maybe-write-db q-rest stations)
                stations))))))

