(ns auto-ap.views.pages.transactions.manual
  (:require [auto-ap.events :as events]
            [auto-ap.forms :as forms]
            [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]]
            [re-frame.core :as re-frame]))

(re-frame/reg-sub
 ::can-submit
 :<- [::forms/form ::form]
 (fn [{ {:keys [data]} :data}]
   (not-empty data)))

(def import-form (forms/vertical-form {:submit-event [::save]
                                       :change-event [::forms/change ::form]
                                       :can-submit [::can-submit]
                                       :id ::form}))

(defn form [{import-completed-event :import-completed}]
  (let [{:keys [data active? error id]} @(re-frame/subscribe [::forms/form ::form])
        {:keys [form-inline horizontal-field field raw-field error-notification submit-button]} import-form]

    (form-inline {}
                 [:div.field
                  [:label.label
                   "Yodlee manual import table"]
                  [:div.control
                   [raw-field
                    [:textarea.textarea {:field [:data]}]]]])))

(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 [::save])
                                                  :can-submit [::can-submit]
                                                  :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 [{:keys [db]} [_ {:keys [imported errors] :as result}]]
   {: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]}})))




