(ns todo.subs
  (:require [re-frame.core :as rf]))

(rf/reg-sub :todos (fn [db _] (:todos db)))
(rf/reg-sub :filter (fn [db _] (:filter db)))
(rf/reg-sub :show-form? (fn [db _] (:show-form? db)))
(rf/reg-sub :editing-todo (fn [db _] (:editing-todo db)))

(rf/reg-sub
  :filtered-todos
  :<- [:todos]
  :<- [:filter]
  (fn [[todos filter-val] _]
    (let [todo-list (sort-by :created-at > (vals todos))]
      (case filter-val
        :all todo-list
        :active (filter #(not (:completed %)) todo-list)
        :completed (filter :completed todo-list)))))

(rf/reg-sub
  :todo-counts
  :<- [:todos]
  (fn [todos _]
    (let [all (vals todos)]
      {:all (count all)
       :active (count (filter #(not (:completed %)) all))
       :completed (count (filter :completed all))})))
