(ns auto-ap.views.pages.admin.import-batches.table
  (:require [auto-ap.routes :as routes]
            [auto-ap.status :as status]
            [auto-ap.subs :as subs]
            [auto-ap.views.components.buttons :as buttons]
            [auto-ap.views.components.grid :as grid]
            [auto-ap.views.pages.data-page :as data-page]
            [auto-ap.views.utils
             :refer
             [action-cell-width date->str dispatch-event pretty-long]]
            [bidi.bidi :as bidi]
            [cemerick.url :as url]
            [re-frame.core :as re-frame]
            [reagent.core :as r]))

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


(re-frame/reg-event-db
 ::unmounted
 (fn [db]
   (status/reset-multi db ::run)))

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

(defn table* [{:keys [data-page]}]
  (let [{:keys [data]} @(re-frame/subscribe [::data-page/page data-page])]
    [grid/grid {:data-page data-page
                :column-count 6}
     [grid/controls data]
     [grid/table {:fullwidth true }
      [grid/header
       [grid/row {}
        [grid/sortable-header-cell {:sort-key "date"
                                    :sort-name "Date"}
         "Date"]

        [grid/sortable-header-cell {:sort-key "source"
                                    :sort-name "Source"}
         "Source"]

        [grid/sortable-header-cell {:sort-key "status"
                                    :sort-name "Status"}
         "Status"]

        [grid/sortable-header-cell {:sort-key "user"
                                    :sort-name "User"}
         "User"]
        [grid/header-cell {:style {:width "7em"}} "Imported"]
        [grid/header-cell {:style {:width "7em"}} "Preexisting"]
        [grid/header-cell {:style {:width "7em"}} "Suppressed"]
        [grid/header-cell {:style {:width (action-cell-width 3)}}]]]
      [grid/body
       (for [{:keys [date source status user-name id imported extant suppressed] :as r} (:data data)]
         ^{:key id}
         [grid/row {:class (:class r) :id id}
          [grid/cell {} (date->str date pretty-long)]
          [grid/cell {} source]
          [grid/cell {} status]
          [grid/cell {} user-name]
          [grid/cell {} imported]
          [grid/cell {} extant]
          [grid/cell {} suppressed]
          [grid/button-cell {}
           [buttons/fa-icon {:href (str (bidi/path-for routes/routes :transactions)
                                        "?"
                                        (url/map->query {:import-batch-id id}))
                             :icon "fa-external-link"}]]
          ])]]]))

(defn table []
  (r/create-class {:component-will-unmount (dispatch-event [::unmounted])
                   :reagent-render (fn [params]
                                     [table* params])}))
