;; 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.

(ns dynamo-replica
  (:require [amazonica.aws.dynamodbv2 :as ddb]
            [datomic.api :as d]
            [auto-ap.datomic :refer [conn]]))

(ddb/delete-table :table-name "sales-replica")

(ddb/create-table
  :table-name "sales-replica"
  :key-schema [{:attribute-name "id" :key-type "HASH"}
               {:attribute-name "date" :key-type "RANGE"}]
  :attribute-definitions
  [{:attribute-name "id" :attribute-type "S"}
   {:attribute-name "date" :attribute-type "S"}
   {:attribute-name "client" :attribute-type "N"}]
  :global-secondary-indexes
  [{:index-name "client_date"
    :key-schema [{:attribute-name "client" :key-type "HASH"}
                 {:attribute-name "date" :key-type "RANGE"}]
    :projection {:projection-type "ALL"}
    :provisioned-throughput
    {:read-capacity-units  500
     :write-capacity-units 500}}]
  :provisioned-throughput
  {:read-capacity-units 500
   :write-capacity-units 500})

(user/init-repl)

(doseq [client ["NGAK"]
        batch  (->> (d/q '[:find [?s ...]
                           :in $ ?c
                           :where
                           [?s :sales-order/client ?c]]
                         (d/db conn)
                         [:client/code client])

                    (partition-all 25)
                    (map (fn [batch]
                           (for [o (d/pull-many (d/db conn)  '[* {:sales-order/charges [*] :sales-order/line-items [*]}] batch)]
                             {:id     (str (:db/id o))
                              :client (:db/id (:sales-order/client o))
                              :date   (str (:sales-order/date o))
                              :total  (:sales-order/total o)
                              #_#_:line-items (into-array (for [i (:sales-order/line-items o)]
                                                        (java.util.HashMap. {:total (:order-line-item/total i)})))}))))]
  (println "Adding 25 ... " (first batch))
  (ddb/batch-write-item :request-items
                        {"sales-replica"
                         (for [item batch]
                           {:put-request {:item item}})})
  (Thread/sleep 50)
  #_(ddb/put-item :table-name "sales-replica"
                :item item))

(doc d/pull-many)

