(ns auto-ap.subs
  (:require [re-frame.core :as re-frame]
            [clojure.string :as str]
            [auto-ap.expense-accounts :refer [expense-accounts chooseable-expense-accounts]]
            [goog.crypt.base64 :as base64]))

(re-frame/reg-sub
 ::client
 (fn [db]
   (get (:clients db) (:client db))))

(re-frame/reg-sub
 ::clients
 (fn [db]
   (when (:user db)
     (vals (:clients db)))))

(re-frame/reg-sub
 ::bank-accounts
 :<- [::clients]
 :<- [::client]
 (fn [[clients client]]
   (println client)
   (if client
     (:bank-accounts client)
     (reduce (fn [result {:keys [bank-accounts]}]
               (into result bank-accounts))
             []
             clients))))

(re-frame/reg-sub
 ::clients-by-id
 (fn [db]
   (when (:user db)
     (:clients db))))

(re-frame/reg-sub
 ::menu
 (fn [db]
   (:menu db)))

(re-frame/reg-sub
 ::modal-state
 (fn [db [_ id]]
   (get (:modal-state db) id)))

(re-frame/reg-sub
 ::token
 (fn [db]
   (:user db)))

(re-frame/reg-sub
 ::vendors
 (fn [db]
   (vals (:vendors db))))

(re-frame/reg-sub
 ::sorted-vendors
 :<- [::vendors]
 (fn [vendors]
   (sort-by :name vendors)))

(re-frame/reg-sub
 ::admin
 (fn [db]
   (:admin db)))

(re-frame/reg-sub
 ::user-editing-vendor
 (fn [db]
   (-> db :user-editing-vendor)))

(re-frame/reg-sub
 ::user
 (fn [db]
   (when (:user db)
     (js->clj (.parse js/JSON (base64/decodeString (second (str/split (:user db) #"\.")))) :keywordize-keys true))))

(re-frame/reg-sub
 ::active-page
 (fn [db]
   (:active-page db)))

(re-frame/reg-sub
 ::pending-invoices
 (fn [db]
   (:pending (:invoices db))))


(re-frame/reg-sub
 ::status
 (fn [db]
   (:status db)))

(re-frame/reg-sub
 ::new-invoice-form
 (fn [db]
   (:new-invoice db)))


(re-frame/reg-sub
 ::expense-accounts
 (fn [db]
   (map (fn [[k v]] (assoc v :id k))
        expense-accounts)))

(re-frame/reg-sub
 ::query-params
 (fn [db]
   (:query-params db)))

(re-frame/reg-sub
 ::chooseable-expense-accounts
 (fn [db]
   (map (fn [[k v]] (assoc v :id k))
        chooseable-expense-accounts)))
