(ns auto-ap.views.pages.transactions.manual
  (:require
   [auto-ap.forms :as forms]
   [auto-ap.forms.builder :as form-builder]
   [auto-ap.schema :as schema]
   [auto-ap.status :as status]
   [auto-ap.subs :as subs]
   [auto-ap.views.components.modal :as modal]
   [auto-ap.views.utils :refer [dispatch-event with-user]]
   [malli.core :as m]
   [re-frame.core :as re-frame]))

(def schema
  (m/schema [:map [:data schema/not-empty-string]]))

(defn form []
  [form-builder/builder {:submit-event [::try-save]
                         :id           ::form
                         :schema schema}

   [form-builder/field-v2  {:required? true
                            :field :data}
    "Yodlee manual import table"
    [:textarea.textarea ]]
   [form-builder/hidden-submit-button]])

(re-frame/reg-event-fx
 ::opening
 (fn [{:keys [db]} _]
   {:dispatch [::modal/modal-requested {:title "Import Transactions"
                                        :body [form]
                                        :confirm {:value "Import"
                                                  :status-from [::status/single ::form]
                                                  :class "is-primary"
                                                  :on-click (dispatch-event [::try-save])
                                                  :close-event [::status/completed ::form]}}]
    :db (-> db
            (forms/start-form ::form
                              {:client-id (:id @(re-frame/subscribe [::subs/client]))
                               :data ""}))}))

(re-frame/reg-event-fx
 ::import-completed
 (fn [_ _]
   {:dispatch [::modal/modal-closed ]}))

(re-frame/reg-event-fx
 ::save
 [with-user (forms/in-form ::form) ]
 (fn [{:keys [db user]}]
   (let [import (:data db)]
     {:http {:token user
             :owns-state {:single ::form}
             :method :post 
             :body (pr-str import)
             :headers {"Content-Type" "application/edn"}
             :uri (str "/api/transactions/batch-upload")
             :on-success [::import-completed]}})))

(re-frame/reg-event-fx
  ::try-save
  [(forms/in-form ::form)]
  (fn [{:keys [db]}]
    (if (not (m/validate schema (:data db)))
      {:dispatch-n [[::status/error ::form [{:message "Please correct any errors and try again"}]]
                    [::forms/attempted-submit ::form]]}
      {:dispatch [::save]})))




