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

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

(re-frame/reg-sub
 ::filters
 :<- [::specific-filters]
 :<- [::subs/vendors-by-id]
 :<- [::subs/query-params]
 (fn [[specific-filters vendors-by-id query-params] ]
   (let [url-filters (-> query-params
                         (select-keys #{:name-like})
                         (update :name-like #(some-> % str)))]
     (merge url-filters specific-filters ))))

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

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

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

(re-frame/reg-event-fx
 ::filters-settled
 (fn [{:keys [db]} [_ & params]]
   {: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 vendor-side-bar []
  [:div
   [:p.menu-label "Name"]

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


