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

(re-frame/reg-event-fx
 ::edit
 (fn  [{:keys [db]} [_ client-id]]
   (println "EDITING")
   {:dispatch [::events/modal-status :auto-ap.views.pages.admin.clients/edit {:visible? true}]
    :db (assoc-in db [:admin :client]
              (get (:clients db) client-id))}))

(re-frame/reg-event-fx
 ::save
 (fn  [{:keys [db]} _]
   (println "saving")
   (let [edited-client (-> (get-in db [:admin :clients])
                            (dissoc :location))]
     {:db (assoc-in db [:admin :client :saving?] true)
      :graphql
      {:token (-> db :user)
       :query-obj {:venia/operation {:operation/type :mutation
                                     :operation/name "EditClient"}
                   :venia/queries [{:query/data [:upsert-client
                                                 {:client edited-client}
                                                 [:id :name :code]
                                                 ]}]}  
       :on-success [::save-complete]
       :on-error [::save-error]}})))

(re-frame/reg-event-fx
 ::save-complete
 (fn  [{:keys [db]} [_ client]]
   {:dispatch [::events/modal-completed :auto-ap.views.pages.admin.clients/edit]
    :db (-> db
        
        (assoc-in [:admin :clients] nil)
        (assoc-in [:clients (:id client)] client))}))

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

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