 (ns swarmpit.component.service.log
-  (:require [material.components :as comp]
+  (:require [material.icon :as icon]
+            [material.components :as comp]
             [swarmpit.component.state :as state]
             [swarmpit.component.mixin :as mixin]
             [swarmpit.ajax :as ajax]
+            [swarmpit.time :as time]
             [swarmpit.routes :as routes]
             [clojure.string :as string]
-            [material.icon :as icon]
             [sablono.core :refer-macros [html]]
             [rum.core :as rum]))
 
 (def line-num (atom 0))
 (def last-scroll (atom 0))
 (def last-glow (atom 0))
+
+(def history-options
+  {"15m" "15 minutes"
+   "30m" "30 minutes"
+   "60m" "1 hour"
+   "4h"  "4 hours"
+   "8h"  "8 hours"
+   "12h" "12 hours"
+   "24h" "24 hours"
+   nil   "all"})
 
 (defn- auto-scroll!
   []

       (map #(assoc-in % [:key] (swap! line-num inc)))))

(defn- log-handler
  [service-id task-id]
  (ajax/get
    (routes/path-for-backend :service-logs {:id service-id})
    {:state      [:fetching]
     :on-success (fn [{:keys [response]}]
                   (let [logs (filter-logs task-id response)]
                     (reset! last-glow (count logs))
                     (state/update-value [:initialized] true state/form-state-cursor)
                     (state/set-value logs state/form-value-cursor)))
     :on-error   #(state/update-value [:error] true state/form-state-cursor)}))

(defn- log-append-handler
  [service-id task-id from-timestamp]
  (ajax/get
    (routes/path-for-backend :service-logs {:id service-id})
    {:state      [:fetching]
     :params     (if from-timestamp {:from from-timestamp})
     :on-success (fn [{:keys [response]}]
                   (state/set-value (-> (state/get-value state/form-value-cursor)
                                        (concat (filter-logs task-id response))) state/form-value-cursor))}))

(defn- init-form-state
  []

(def mixin-refresh-form
  (mixin/refresh-form
    (fn [{{:keys [id taskId]} :params}]
      (let [state (state/get-value state/form-state-cursor)]
        (when (not (:fetching state))
          (log-append-handler id
                              taskId
                              (-> (state/get-value state/form-value-cursor)
                                  (last)
                                  :timestamp)))))))

(def mixin-init-form
  (mixin/init-form
    (fn [{{:keys [id taskId]} :params}]
      (init-form-state)
      (service-handler id)
      (log-handler id taskId "15m"))))

(rum/defc line < rum/static [service item index]
  [:div
   [:a.log-info {:href (routes/path-for-frontend :service-task-log {:id     (:serviceName service)
                                                                    :taskId (:task item)})}
    (str (subs (:task item) 0 7))]
   [:span {:class (if (< @last-glow index)
                    (do (swap! last-glow inc)
