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

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

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

(defn table [{:keys [status page]}]
  (let [params @(re-frame/subscribe [::params])]
    [grid/grid {:status status
                :on-params-change (fn [p]
                                    (re-frame/dispatch [::params-changed p]))
                :params  params
                :column-count 4}
     [grid/controls page]
     [grid/table {:fullwidth true}
      [grid/header
       [grid/row {}
        [grid/header-cell {} "User"]
        [grid/header-cell {} "Role"]
        [grid/header-cell {} "Clients"]
        [grid/header-cell {:style {:width (action-cell-width 1)}} ]]]
      [grid/body
       (for [{:keys [id name role clients] :as c} (:data page)]
         ^{:key (str name "-" id )}
         [grid/row {:class (:class c) :id id}
          [grid/cell {} name]
          [grid/cell {} role]
          [grid/cell {} (str/join ", " (map :name clients))]
          [grid/cell {}
           [buttons/fa-icon {:event [::form/editing c]
                             :icon "fa-pencil"}]]])]]]))
