(ns auto-ap.views.pages.admin.import-batches
  (:require
   [auto-ap.subs :as subs]
   [auto-ap.shared-views.admin.side-bar :refer [admin-side-bar]]
   [auto-ap.views.components.layouts :refer [side-bar-layout]]
   [auto-ap.views.pages.admin.import-batches.table :as table]
   [auto-ap.views.pages.data-page :as data-page]
   [auto-ap.views.utils :refer [dispatch-event with-user]]
   [clojure.set :as set]
   [re-frame.core :as re-frame]
   [vimsical.re-frame.fx.track :as track]))

(def default-read [:user-name :date :source :status :id :imported :suppressed :extant])

(re-frame/reg-event-fx
 ::params-change
 [with-user ]
 (fn [{:keys [user]} [_ params]]
   {:graphql {:token user
              :owns-state {:single [::data-page/page ::page]}
              :query-obj {:venia/queries [{:query/data [:import_batch_page
                                                        {:filters {:sort (:sort params)
                                                                   :start (:start params 0)
                                                                   :per-page (:per-page params)}}
                                                        [[:data default-read]
                                                         :total
                                                         :start
                                                         :end]]
                                           :query/alias :result}]} 
              :on-success (fn [result]
                            [::data-page/received ::page
                             (set/rename-keys (:result result)
                                              {:import-batches :data})])}}))


(re-frame/reg-event-fx
 ::mounted
 (fn [_]
   {::track/register {:id ::params
                      :subscription [::data-page/params ::page]
                      :event-fn (fn [params]
                                  [::params-change params])}}))

(re-frame/reg-event-fx
 ::unmounted
 (fn [{:keys [db]}]
   {:dispatch [::data-page/dispose ::page]
    ::track/dispose {:id ::params}}))

;; VIEWS
(def import-batch-content
  (with-meta
    (fn []
      (let [user @(re-frame/subscribe [::subs/user])]
        [:div 
         [:h1.title "Import Batches"]
         (when (= "admin" (:user/role user))
           [:div 
            [:div.is-pulled-right
             [:div.buttons]]
            [table/table {:id        :import-batches
                          :data-page ::page}]])]))
    {:component-did-mount (dispatch-event [::mounted ])
     :component-will-unmount #(re-frame/dispatch-sync [::unmounted])}))

(defn import-batches-page []
  [side-bar-layout {:side-bar [admin-side-bar {}]
                    :main [import-batch-content]}])

