(ns auto-ap.datomic.yodlee2
  (:require [datomic.api :as d]
            [auto-ap.datomic :refer [uri remove-nils merge-query apply-pagination apply-sort-3 add-sorter-fields conn]]
            [auto-ap.graphql.utils :refer [limited-clients]]
            [auto-ap.parse :as parse]
            [clj-time.coerce :as c]
            [clojure.set :refer [rename-keys]]
            [clojure.string :as str]
            [clojure.tools.logging :as log]))

(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 [(d/db (d/connect uri))]}
         
         (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]]}}) )
       

       (d/query)
       (apply-sort-3 args)
       (apply-pagination args)))


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


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

(defn get-by-id [id]
  (-> (d/db (d/connect uri))
      (d/pull  default-read id)
      (<-datomic)))

