(ns auto-ap.events.admin.companies
  (:require [re-frame.core :as re-frame]
            [auto-ap.db :as db]
            [auto-ap.routes :as routes]
            [auto-ap.effects :as effects]
            [auto-ap.entities.companies :as entity]
            [bidi.bidi :as bidi]))

(re-frame/reg-event-db
 ::edit
 (fn  [db [_ company-id]]
   (assoc-in db [:admin :company]
             (get (:companies db) company-id))))

(re-frame/reg-event-fx
 ::save
 (fn  [{:keys [db]} _]
   (let [edited-company (get-in db [:admin :company])]
     {:db (assoc-in db [:admin :company :saving?] true)
      :http {:method :put
             :token (:user db)
             :body (pr-str edited-company)
             :headers {"Content-Type" "application/edn"}
             :uri (str "/api/companies/" (:id edited-company))
             :on-success [::save-complete]
             :on-error [::save-error]}})))

(re-frame/reg-event-db
 ::save-complete
 (fn  [db [_ company]]
   (-> db
       
       (assoc-in [:admin :company] nil)
       (assoc-in [:companies (:id company)] company))))

(re-frame/reg-event-db
 ::save-error
 (fn  [db [_ company]]
   (-> db
       (assoc-in [:admin :company :saving?] false)
       (assoc-in [:admin :company :error] true))))

(re-frame/reg-event-db
 ::change
 (fn  [db [_ path value]]
   (assoc-in db (concat [:admin :company] path)
             value)))
