(ns auto-ap.views.components.sorter
  (:require [re-frame.core :as re-frame]
            [auto-ap.subs :as subs]
            [auto-ap.views.utils :refer [date->str]]
            [reagent.core :as reagent]
            [clojure.string :as str]
            [cljs-time.format :as format]))
(defn toggle-sort-by [params sort-key sort-name asc]
  (let [[found? sort] (reduce
                       (fn [[found? sort] sort-item]
                         (if (= sort-key (:sort-key sort-item))
                           [true (conj sort
                                       (update sort-item :asc not))]
                           [found? (conj sort sort-item)]))
                       [false []]
                       (:sort params))
        sort (if found?
               sort
               (conj sort {:sort-key sort-key
                           :sort-name sort-name
                           :asc true}))]

    (-> params
        (assoc :sort sort))))

(defn sort-icon [which sort asc]
  (let [sort-item (first (filter #(= which (:sort-key %)) sort))]
    (cond
      (and sort-item (:asc sort-item))
      [:span.icon
       [:i.fa.fa-sort-up]]

      (and sort-item (not (:asc sort-item)))
      [:span.icon
       [:i.fa.fa-sort-down]]

      :else
      [:span.icon
       [:i.fa.fa-sort]])))


(defn sorted-column [{:keys [on-sort sort-key sort sort-name asc style class]} & rest]
  [:th {:on-click (fn [e]
                    (on-sort
                     (toggle-sort-by {:sort sort} sort-key sort-name asc)))
        :style style
        :class class}
   rest 
   (sort-icon sort-key sort asc)])
