(ns auto-ap.views.pages.reports
  (:require
   [auto-ap.subs :as subs]
   [auto-ap.views.components.layouts :refer [side-bar-layout]]
   [auto-ap.views.pages.data-page :as data-page]
   [auto-ap.shared-views.company.sidebar
    :as side-bar
    :refer [company-side-bar]]
   [auto-ap.views.pages.reports.table :as table]
   [auto-ap.views.utils :refer [with-user]]
   [clojure.set :as set]
   [re-frame.core :as re-frame]
   [reagent.core :as reagent]
   [vimsical.re-frame.fx.track :as track]))

(defn data-params->query-params [params]
  {:start (:start params 0)
   :sort (:sort params)
   :per-page (:per-page params)
   :client-id (:id @(re-frame/subscribe [::subs/client]))})


(re-frame/reg-event-fx
 ::params-change
 [with-user]
 (fn [{:keys [user]} [_ params]]
   {:graphql {:token user
              :owns-state {:single [::data-page/page ::page]}
              :query-obj {:venia/queries [[:report-page
                                           {:filters (data-params->query-params params)}
                                           [[:reports [:id
                                                       :name
                                                       :created
                                                       :creator
                                                       :url]]
                                            :total
                                            :start
                                            :end]]]} 
              :on-success (fn [result]
                            [::data-page/received ::page (set/rename-keys (:report-page result)
                                                                          {:reports :data})])}}))

(re-frame/reg-event-fx
 ::unmounted
 (fn [_ _]
   {:dispatch [::data-page/dispose ::page]
    ::track/dispose {:id ::params}}))

(re-frame/reg-event-fx
 ::mounted
 (fn [_ _]
   {::track/register {:id ::params
                      :subscription [::data-page/params ::page]
                      :event-fn (fn [params] [::params-change params])}}))



(defn ledger-content []
  (let [_ @(re-frame/subscribe [::subs/client])]
    [:div 
     [:h1.title "Reports"]
     [table/table {:id :reports
                   :data-page ::page}]]))


(defn reports-page []
  (let [user (re-frame/subscribe [::subs/user])]
    (reagent/create-class
     {:display-name "report-page"
      :component-did-mount #(re-frame/dispatch [::mounted])
      :component-will-unmount #(re-frame/dispatch [::unmounted])
      :reagent-render
      (fn []
        (println "ROLE" (:user/role @user))
        (if (not= "manager" (:user/role @user))
          [side-bar-layout
           {:side-bar [company-side-bar {:data-page ::page}]
            :main [ledger-content]}]
          [:div "Not authorized"]))})))

