(ns auto-ap.views.pages.company.yodlee2.table
  (:require [auto-ap.status :as status]
            [auto-ap.subs :as subs]
            [auto-ap.views.components.buttons :as buttons]
            [auto-ap.views.components.grid :as grid]
            [auto-ap.views.components.modal :as modal]
            [auto-ap.views.pages.company.yodlee2.form :as form]
            [auto-ap.views.utils :refer [->$ action-cell-width date->str with-user dispatch-event]]
            [re-frame.core :as re-frame]))

(re-frame/reg-event-fx
 ::refreshed
 [with-user ]
 (fn [_ _]
   ;; this is tracked in yodlee main, for refreshing
   {}))

(re-frame/reg-event-fx
 ::request-refresh
 [with-user ]
 (fn [{:keys [user]} [_ provider-account client-id ]]
   {:http {:token user
           :method :post 
           :headers {"Content-Type" "application/edn"}
           :uri (str "/api/yodlee2/provider-accounts/refresh/")
           :owns-state {:multi ::refresh
                        :which provider-account}
           :body {:client-id client-id
                  :provider-account-id provider-account}
           :on-success [::refreshed provider-account]}}))

(re-frame/reg-event-fx
 ::provider-account-deleted
 (fn [_ _]
   {:dispatch [::modal/modal-closed ]}))



(re-frame/reg-event-fx
  ::request-login-form
  [with-user ]
  (fn [{:keys [user]} [_ provider-account client-id]]
    {:http {:token      user
            :method     :get 
            :headers    {"Content-Type" "application/edn"}
            :uri        (str "/api/yodlee2/fastlink?client-id=" client-id)
            :owns-state {:multi ::request-login-form
                         :which (:id provider-account)}
            :on-success [::form/reauthenticate-start provider-account]}}))

(re-frame/reg-event-fx
 ::delete-provider-account
 [with-user ]
 (fn [{:keys [user]} [_ provider-account-id ]]
   {:http {:token user
           :method :post 
           :owns-state {:single ::delete-provider-account}
           :headers {"Content-Type" "application/edn"}
           :uri (str "/api/yodlee2/provider-accounts/delete/" )
           :body {:client-id (:id @(re-frame/subscribe [::subs/client]))
                  :provider-account-id provider-account-id}
           :on-success [::provider-account-deleted provider-account-id]
           }}))

(re-frame/reg-event-fx
 ::delete-requested
 [with-user]
 (fn [_ [_ account-id]]
   {:dispatch 
    [::modal/modal-requested {:title "Delete Provider account "
                              :body [:div "Are you sure you want to delete provider account " account-id "?"]
                              :confirm {:value "Delete provider account"
                                        :status-from [::status/single ::delete-provider-account]
                                        :class "is-danger"
                                        :on-click (dispatch-event [::delete-provider-account account-id])
                                        :close-event [::status/completed ::delete-provider-account]}
                              :cancel? true}]}))

(re-frame/reg-event-fx
 ::params-changed
 (fn [{:keys [db]} [_ p]]
   {:db (assoc db ::params p)}))

(re-frame/reg-sub
 ::params
 (fn [db]
   (-> db ::params)))

(defn table [{:keys [status page]}]
  (let [params @(re-frame/subscribe [::params])
        statuses @(re-frame/subscribe [::status/multi ::refresh])
        login-statuses @(re-frame/subscribe [::status/multi ::request-login-form])
        is-admin? @(re-frame/subscribe [::subs/is-admin?])]
    [grid/grid {:status status
                :on-params-change (fn [p]
                                    (re-frame/dispatch [::params-changed p]))
                :params  params
                :column-count 4}
     [grid/controls page]
     [grid/table {:fullwidth true}
      [grid/header
       [grid/row {}
        [grid/header-cell {:style {:width "18em"}} "Provider Account"]
        [grid/header-cell {:style {:width "20em"}} "Status"]
        [grid/header-cell {:style {:width "20em"}} "Detailed Status"]
        [grid/header-cell {:style {:width "12em"}} "Last Updated"]
        [grid/header-cell {} "Accounts"]
        [grid/header-cell {:style {:width (action-cell-width 3)}} ]]]
      [grid/body
       (for [{:keys [id name accounts status detailed-status last-updated] :as c} (:data page)]
         ^{:key (str name "-" id )}
         [grid/row {:class (:class c) :id id}
          [grid/cell {} id]
          [grid/cell {} status]
          [grid/cell {} detailed-status]
          [grid/cell {} (date->str last-updated)]
          [grid/cell {}
           [:ul
            (for [a accounts]
              ^{:key (:id a)}
              [:li (:name a) " - " (:number a) [:div.tag (->$ (:available-balance a))]])]]
          [grid/cell {}
           (when is-admin? 
             [:div.buttons 
              [buttons/fa-icon {:event
                                [::request-login-form (:id c) (:id (:client c))]
                                :class (status/class-for (get login-statuses (:id c)))
                                :icon  "fa-pencil"}]
              [buttons/fa-icon {:event [::request-refresh (:id c) (:id (:client c))]
                                :class (status/class-for (get statuses (:id c)))
                                :icon  "fa-refresh"}]
              [buttons/fa-icon {:event [::delete-requested (:id c)]
                                :icon  "fa-times"}]])]])]]]))
