(ns auto-ap.views.pages.admin.jobs.table
  (:require
   [auto-ap.status :as status]
   [auto-ap.subs :as subs]
   [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]]
   [cljs-time.core :as time]
   [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/header-cell {} 
         "Start Date"]

        [grid/header-cell 
         "End Date"]

        [grid/header-cell 
         "Duration"]
        [grid/header-cell 
         "Job Name"]

        [grid/header-cell {}
         "Status"]

        [grid/header-cell {:style {:width (action-cell-width 3)}}]]]
      [grid/body
       (for [{:keys [start-date end-date status name] :as r} (:data data)]
         ^{:key (str start-date)}
         [grid/row {:class (:class r) :id (str start-date)}
          [grid/cell {} (some-> start-date (date->str pretty-long))]
          [grid/cell {} (some-> end-date (date->str pretty-long))]
          [grid/cell {} (when (and start-date end-date)
                          (str (time/in-minutes (time/interval start-date end-date)) " minutes"))]
          [grid/cell {} name]
          [grid/cell {} status]
          
          [grid/button-cell {}
           ]
          ])]]]))

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