;; This buffer is for Clojure experiments and evaluation.

;; Press C-j to evaluate the last expression.

;; You can also press C-u C-j to evaluate the expression and pretty-print its result.

(require '[clj-http.client :as client])
(require ' [clojure.data.json :as json])


(defn upsert-schema []
  (client/post
    "http://localhost:8983/solr/gettingstarted/schema"
    {:headers {"Content-Type" "application/json"}
                 :method "POST"
     :body    (json/write-str {"add-field" [{"name" "client-id"
                                          "type" "string"}
                                         {"name" "order-date"
                                          "type" "pdate"}]})
                 }))

(defn load-sales-orders []
  (clojure.pprint/pprint 
    (doseq [[client code] (dc/q '[:find ?c ?code :where [?c :client/code ?code]] (dc/db conn))
            :let [_ (println "loading" code)]
            
            batch (->> (dc/qseq '[:find ?so ?date ?client-id
                                  :in $ ?client-id
                                  :where
                                  [?so :sales-order/client ?client-id]
                                  [?so :sales-order/date ?date]
                                  ]
                                (dc/db conn)
                                client)
                       (map (fn [[so date client-id]]
                              {"id"         so
                               "order-date" (str date)
                               "client-id"  (str client-id)}))
                       (partition-all 1000)
                       )]
      (print ".")
      (flush)
      (client/post
        "http://localhost:8983/solr/gettingstarted/update?commitWithin=60000"
        {:headers {"Content-Type" "application/json"}
         :method  "POST"
         :body    (json/write-str batch)
         }))))


(comment 
  (try 
    (upsert-schema)
    (catch Exception e
      (println  e)))

  (load-sales-orders)

  (dc/pull (dc/db conn) '[:client/code :db/id] [:client/code "NGOP"])

  )
