(ns auto-ap.views.pages.admin.clients.side-bar
  (:require
   [re-frame.core :as re-frame]
   [auto-ap.views.utils :refer [dispatch-value-change]]
   [auto-ap.subs :as subs]))

(re-frame/reg-sub
 ::specific-filters
 (fn [db ]
   (::filters db nil)))

(re-frame/reg-sub
 ::filters
 :<- [::specific-filters]
 :<- [::subs/query-params]
 (fn [[specific-filters _ query-params] ]
   (let [url-filters (-> query-params
                         (select-keys #{:name
                                        :code}))
         url-filters {:name  (str (:name url-filters))
                      :code (str (:code url-filters))}]
     (merge url-filters specific-filters ))))

(re-frame/reg-sub
 ::filter
 :<- [::filters]
 (fn [filters [_ which]]
   (get filters which)))

(re-frame/reg-sub
 ::filter-params
 :<- [::settled-filters]
 :<- [::filters]
 :<- [::subs/active-page]
 (fn [[settled-filters filters _ ]]
   (let [filters (or settled-filters filters)]
     {:name (:name filters)
      :code (:code filters)})))

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

(re-frame/reg-event-fx
 ::filters-settled
 (fn [{:keys [db]} _]
   {:db (assoc db ::settled-filters @(re-frame/subscribe [::filters]))}))

(re-frame/reg-event-fx
 ::filter-changed
 (fn [{:keys [db]} [_ & params]]
   (let [[a b c] params
         [which val] (if (= 3 (count params))
                       [(into [a] b) c]
                       [[a] b])]
     {:db (assoc-in db (into [::filters] which) val)
      :dispatch-debounce {:event [::filters-settled]
                          :time 800
                          :key ::filters}})))


(defn client-side-bar []
  [:div
   [:p.menu-label "Name"]

   [:div.field
    [:div.control [:input.input {:placeholder "Harry's Food Products"
                                 :value @(re-frame/subscribe [::filter :name])
                                 :on-change (dispatch-value-change [::filter-changed :name])} ]]]

   [:p.menu-label "Code"]

   [:div.field
    [:div.control [:input.input {:placeholder "CBC"
                                 :value @(re-frame/subscribe [::filter :code])
                                 :on-change (dispatch-value-change [::filter-changed :code])} ]]]])


