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

(re-frame/reg-sub
 ::company
 (fn [db]
   (get (:companies db) (:company db))))

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

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

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

(re-frame/reg-sub
 ::modal-state
 (fn [db [_ id]]
   (println "ID" 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
 ::admin
 (fn [db]
   (:admin db)))

(re-frame/reg-sub
 ::user
 (fn [db]
   (when (:user db)
     (let [{:strs [name] :as x} (js->clj (.parse js/JSON (base64/decodeString (second (str/split (:user db) #"\.")))))]
       {:name name}))))

(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)))
