(ns auto-ap.views.pages.admin.clients.table
  (:require [auto-ap.subs :as subs]
            [clojure.string :as str]
            [re-frame.core :as re-frame]
            [auto-ap.views.pages.admin.clients.form :as form]
            [auto-ap.views.utils :refer [action-cell-width]]
            [auto-ap.views.components.grid :as grid]
            [auto-ap.views.components.buttons :as buttons]))

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

(re-frame/reg-event-fx
 ::params-changed
 (fn [{:keys [db]} [_ p]]
   {:db (assoc db ::params p)}))

(re-frame/reg-sub
 ::params
 :<- [::specific-params]
 :<- [::subs/query-params]
 (fn [[specific-params query-params]]
   (merge (select-keys query-params #{:start :sort}) specific-params )))


(defn clients-table [{:keys [page status]}]
  [grid/grid {:on-params-change (fn [p]
                                  (re-frame/dispatch [::params-changed p]))
              :status status
              :params @(re-frame/subscribe [::params])
              :column-count 5}
   [grid/controls page]
   [grid/table {:fullwidth true}
    [grid/header 
     [grid/row {}
      [grid/header-cell {} "Name"]
      [grid/header-cell {:style {:width "20em"}} "Code"]
      [grid/header-cell {} "Locations"]
      [grid/header-cell {} "Email"]
      [grid/header-cell {:style {:width (action-cell-width 1)}}]]
     ]
    [grid/body
     (for [{:keys [id name email code locations] :as c} (:data page)]
       ^{:key (str name "-" id )}
       [grid/row {:id id}
        [grid/cell {} name]
        [grid/cell {} code]
        [grid/cell {} (str/join ", " locations)]
        [grid/cell {} email]
        [grid/cell {} [buttons/fa-icon {:event [::form/editing id]
                                        :icon :fa-pencil}]]])]]])
