(ns lineup.events
  (:require
   [lineup.db :as db]
   [re-frame.core :as re-frame]))

(re-frame/reg-event-db
 ::initialize-db
 (fn [_ _]
   db/default-db))

(re-frame/reg-event-db
 ::toggle-mode
 (fn [db [_ new-mode]]
   (assoc db :mode new-mode)))

(re-frame/reg-event-db
 ::select-selecting
 (fn [db [_ which]]
   (assoc db :selecting which)))

(re-frame/reg-event-db
 ::toggle-task-complete
 (fn [db [_ which]]
   (update-in
    db
    [:schedule :tasks]
    (comp
     vec
     (partial map-indexed #(if (= %1 which)
                             (update %2 :complete? not)
                             %2))))))

(re-frame/reg-event-fx
 ::select-task
 (fn [{:keys [db]} [_ which id]]
   (let [old-tasks (get-in db [:schedule :tasks])
         new-task {:ref id}
         new-tasks (if (>= which (count old-tasks))
                     (conj old-tasks new-task)
                     (vec
                      (concat
                       (subvec old-tasks 0 which)
                       [new-task]
                       (subvec old-tasks (inc which)))))]
     {:db (assoc-in db [:schedule :tasks] new-tasks)
      :fx [[:dispatch [::select-selecting nil]]]})))

(re-frame/reg-event-db
 ::remove-task
 (fn [db [_ which]]
   (let [old-tasks (get-in db [:schedule :tasks])
         new-tasks (vec
                    (concat
                     (subvec old-tasks 0 which)
                     (subvec old-tasks (inc which))))]
     (assoc-in db [:schedule :tasks] new-tasks))))
