(ns auto-ap.views.pages.admin.users
  (:require
   [auto-ap.effects.forward :as forward]
   [auto-ap.status :as status]
   [auto-ap.utils :refer [replace-by]]
   [auto-ap.shared-views.admin.side-bar :refer [admin-side-bar]]
   [auto-ap.views.components.grid :as grid]
   [auto-ap.views.components.layouts :refer [side-bar-layout]]
   [auto-ap.views.pages.admin.users.form :as form]
   [auto-ap.views.pages.admin.users.table :as table]
   [re-frame.core :as re-frame]
   [reagent.core :as reagent]))

(re-frame/reg-sub
 ::params
 :<- [::table/params]
 (fn [table-params]
   table-params))

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

(re-frame/reg-sub
 ::page
 :<- [::params]
 :<- [::users]
 (fn [[params all-users]]
   (assoc (grid/virtual-paginate-controls (:start params ) (:per-page params) all-users )
          :data (grid/virtual-paginate (:start params) (:per-page params) all-users))))

(re-frame/reg-event-fx
 ::mounted
 (fn [{:keys [db]} _]
   {:graphql {:token (:user db)
              :owns-state {:single ::page}
              :query-obj {:venia/queries [[:user
                                           [:name
                                            :id
                                            :role
                                            [:clients [:id :name]]]]]} 
              :on-success [::received]}
    ::forward/register {:id ::edited-user
                        :events #{::form/saved}
                        :event-fn (fn [[_ query-result]]
                                    [::saved query-result])}}))

(re-frame/reg-event-fx
 ::unmounted
 (fn [_ _]
   {::forward/dispose {:id ::edited-user}}))


(re-frame/reg-event-db
 ::saved
 (fn [db [_ query-result]]
   (-> db
       (update ::users
               replace-by
               :id
               (assoc (:edit-user query-result) :class "live-added")))))

(re-frame/reg-event-db
 ::received
 (fn [db [_ d]]
   (assoc-in db [::users] (:user d))))


(defn users-table []
  [table/table {:page @(re-frame/subscribe [::page])
                :status @(re-frame/subscribe [::status/single ::page])}])


(defn admin-users-content []
  [:div
   [:h1.title "Users"]
   [users-table]])


(defn admin-users-page []
  (reagent/create-class
   {:component-will-unmount #(re-frame/dispatch [::unmounted])
    :component-did-mount #(re-frame/dispatch [::mounted])
    :reagent-render (fn []
                      [side-bar-layout {:side-bar [admin-side-bar {}]
                                        :main [admin-users-content]}])}))

