(ns auto-ap.background.vendor
  (:require [auto-ap.datomic.invoices :as d-invoices]
            [auto-ap.datomic :refer [uri conn]]
            [datomic.api :as d]
            [auto-ap.time :as time]
            [clj-time.coerce :as coerce]
            [mount.core :as mount]
            [yang.scheduler :as scheduler]
            [unilog.context :as lc]
            [clojure.tools.logging :as log]))

(defn refresh-vendor-usages []
  (lc/with-context {:source "refreshing vendor-usages"}

    (try
      (->> {:query {:find ['?v '?c '(count ?e)]
                    :in ['$]
                    :where ['[?v :vendor/name]
                            '(or-join [?v ?c ?e]
                                      (and 
                                       [?e :invoice/vendor ?v]
                                       [?e :invoice/client ?c])
                                      (and
                                       [?e :transaction/vendor ?v]
                                       [?e :transaction/client ?c])
                                      (and
                                       [?e :journal-entry/vendor ?v]
                                       [?e :journal-entry/client ?c]))]}
            :args [(d/db conn)]}
           (d/query)
           (map (fn [[v c cnt]]
                  #:vendor-usage {:vendor v
                                  :client c
                                  :key (str v "-" c)
                                  :count cnt}))
           (d/transact conn)
           deref)
      (log/info "updated vendor usage")
      (catch Exception e
        (log/error e)))))

(mount/defstate refresh-vendor-usages-worker
  :start (scheduler/every (* 60 60 1000) refresh-vendor-usages)
  :stop (scheduler/stop refresh-vendor-usages))
