(ns auto-ap.datomic.clients
  (:require [auto-ap.datomic :refer [conn uri]]
            [clj-time.coerce :as coerce]
            [clojure.tools.logging :as log]
            [datomic.api :as d]))

(defn cleanse [e]
  (-> e
      (assoc :client/yodlee-provider-accounts (get e :yodlee-provider-account/_client))
      (update :client/location-matches
              (fn [lms]
                (map #(assoc % :location-match/match (first (:location-match/matches %))) lms)))
      (update :client/bank-accounts
              (fn [bas]
                (map (fn [i ba]
                       (-> ba
                           (update :bank-account/type :db/ident )
                           (update :bank-account/start-date #(some-> % (coerce/to-date-time)))
                           (update :bank-account/sort-order (fn [so] (or so i)))))
                     (range) bas)))))
(defn get-all []
  (->> (d/q '[:find (pull ?e [*
                              {:client/address [*]}
                              {:client/bank-accounts [* {:bank-account/type [*]
                                                         :bank-account/yodlee-account [:yodlee-account/name :yodlee-account/id :yodlee-account/number]
                                                         :bank-account/intuit-bank-account [:intuit-bank-account/name :intuit-bank-account/external-id :db/id]}
                                                      ]}
                              {:yodlee-provider-account/_client [*]}])
              :where [?e :client/name]]
            (d/db (d/connect uri)))
       (map first)
       (map cleanse)
       
       ))
(defn get-by-id [id]
  
  (->> 
   (d/pull (d/db conn ) 
           '[* {:client/bank-accounts [* {:bank-account/type [*]
                                          :bank-account/yodlee-account [:yodlee-account/name :yodlee-account/id :yodlee-account/number]
                                          :bank-account/intuit-bank-account [:intuit-bank-account/name :intuit-bank-account/external-id :db/id]}]}
             {:yodlee-provider-account/_client [*]}]
         id)
   (cleanse)))

(defn code->id [code]
  (->> 
   (d/query (-> {:query {:find ['?e]
                         :in ['$ '?code]
                         :where [['?e :client/code '?code ]]}
                 :args [(d/db (d/connect uri)) code]}))
   (first)
   (first)))

(defn assoc-image [code image]
  @(d/transact (d/connect uri)
               [{ :client/code code
                 :client/signature-file (str "https://s3.amazonaws.com/integreat-signature-images/" image)}]))


#_(d/pull (d/db (d/connect uri)) '[*] [:client/code "FTLO"])
#_(assoc-image "FTLO" "Fratello.jpg" )
