(ns auto-ap.datomic.yodlee2
  (:require
   [auto-ap.datomic
    :refer [add-sorter-fields apply-pagination apply-sort-3 merge-query conn pull-many]]
   [auto-ap.graphql.utils :refer [limited-clients]]
   [clj-time.coerce :as c]
   [datomic.client.api :as dc]))

(def default-read '[*])

(defn <-datomic [x]
  (-> x (update  :yodlee-provider-account/last-updated c/from-date)))

(defn raw-graphql-ids [db args]
  (->> (cond-> {:query {:find []
                        :in ['$]
                        :where ['[?e :yodlee-provider-account/id]]}
                :args [db]}

         (limited-clients (:id args))
         (merge-query {:query {:in ['[?xx ...]]
                               :where ['[?e :yodlee-provider-account/client ?xx]]}
                       :args [ (set (map :db/id (limited-clients (:id args))))]})

         (:client-id args)
         (merge-query {:query {:in ['?client-id]
                               :where ['[?e :yodlee-provider-account/client ?client-id]]}
                       :args [ (:client-id args)]})

         (:client-code args)
         (merge-query {:query {:in ['?client-code]
                               :where ['[?e :yodlee-provider-account/client ?client-id]
                                       '[?client-id :client/code ?client-code]]}
                       :args [ (:client-code args)]})

         (:sort args) (add-sorter-fields {"status" ['[?e :yodlee-provider-account/status ?sort-status]]}
                                         args)
         true
         (merge-query {:query {:find ['?e ]
                               :where ['[?e :yodlee-provider-account/id]]}}) )

       (dc/q)
       (apply-sort-3 args)
       (apply-pagination args)))


(defn graphql-results [ids db _]
  (let [results (->> (pull-many db default-read ids)
                     (group-by :db/id))]
    (->> ids
         (map results)
         (map first)
         (mapv <-datomic))))


(defn get-graphql [args]
  (let [db (dc/db conn)
        {ids-to-retrieve :ids matching-count :count} (raw-graphql-ids db args)]
    [(->> (graphql-results ids-to-retrieve db args))
     matching-count]))

