(ns auto-ap.views.pages.paid-invoices
  (:require [re-frame.core :as re-frame]
            [auto-ap.entities.companies :as company]
            [auto-ap.entities.vendors :as vendor]
            [auto-ap.events :as events]
            [auto-ap.views.utils :refer [dispatch-event]]
            [auto-ap.utils :refer [by]]
            [auto-ap.views.pages.check :as check]
            [auto-ap.views.components.invoice-table :refer [invoice-table] :as invoice-table]
            [auto-ap.subs :as subs]))




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

(re-frame/reg-sub
 ::params
 (fn [db]
   (-> db (::params {}))))

(re-frame/reg-event-fx
 ::params-change
 (fn [cofx [_ params]]
   (println "HERE")

   
   {:db (-> (:db cofx)
            (assoc-in [:status :loading] true)
            (assoc-in [::params] params))
    :graphql {:token (-> cofx :db :user)
              :query-obj (invoice-table/query (assoc params :imported true :status "paid")) 
              :on-success [::received]}}))

(re-frame/reg-event-db
 ::received
 (fn [db [_ data]]
   (-> db
       (assoc ::invoice-page (first (:invoice-page data)))
       (assoc-in [:status :loading] false))))

(re-frame/reg-event-fx
 ::invalidated
 (fn [cofx [_ params]]
   {:dispatch [::params-change @(re-frame/subscribe [::params])]}))

(def paid-invoices-page
  
  (with-meta
    (fn []
      (let [current-company @(re-frame/subscribe [::subs/company])]
        [:div 
         [:h1.title "Paid invoices"]
         
         
         [invoice-table {:id :paid
                         :params (re-frame/subscribe [::params])
                         :invoice-page (re-frame/subscribe [::invoice-page])
                         :status (re-frame/subscribe [::subs/status])
                         :on-params-change (fn [params]
                                             (re-frame/dispatch [::params-change params]))
                         :check-boxes false}]]))
    {:component-will-mount #(do (println "HERE2") (re-frame/dispatch-sync [::params-change {}])) }))

