(ns dmr.events
  (:require
   [clojure.string :refer [trim]]
   [re-frame.core :as re-frame]
   [dmr.db :as db]
   [day8.re-frame.tracing :refer-macros [fn-traced]]))


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

(re-frame/reg-event-db
 ::update-cmdline
 (fn-traced [db [_ current]]
  (assoc-in db [:cmdline :current] current)))

(defn execute
    [db cmdline]
 (let [spells (db :spells)
       equipment (db :equipment)
       cmd (keyword cmdline)]
  ; TODO: Replace with the 'match' macro
  (cond
   (contains? spells cmd) {:spell (spells cmd)}
   (contains? equipment cmd) {:equipment (equipment cmd)}
   :else {:err (str "Unknown command '" cmdline "'")})))

(re-frame/reg-event-db
 ::submit-cmd
 (fn-traced [db _]
  (let [cmdline (-> db (get-in [:cmdline :current]) trim)
        not-empty? seq]
    ; TODO replace this with a "->when" macro so that we
    ; don't always have to prefix with a conditional
    (cond-> db
     true (update-in [:cmdline :current] (constantly nil))
     (not-empty? cmdline)
     (as-> db
       (let [output (execute db cmdline)]
           (update-in db [:cmdline :history] conj
               {:input cmdline :output output})))))))