(ns auto-ap.views.pages.company.yodlee2
  (:require
   [auto-ap.effects.forward :as forward]
   [auto-ap.status :as status]
   [auto-ap.subs :as subs]
   [auto-ap.views.components.grid :as grid]
   [auto-ap.views.components.layouts :refer [side-bar-layout]]
   [auto-ap.shared-views.company.sidebar :refer [company-side-bar]]
   [auto-ap.views.pages.company.yodlee2.table :as table]
   [auto-ap.views.utils :refer [dispatch-event with-user]]
   [re-frame.core :as re-frame]
   [reagent.core :as reagent]
   [vimsical.re-frame.cofx.inject :as inject]))

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

(re-frame/reg-sub
 ::params
 :<- [::table/params]
 (fn [table-params]
   table-params))

(re-frame/reg-sub
 ::yodlee-provider-accounts
 (fn [db]
   (::yodlee-provider-accounts db)))

(re-frame/reg-sub
 ::page
 :<- [::params]
 :<- [::yodlee-provider-accounts]
 (fn [[params all-yodlee-provider-accounts]]
   (assoc (grid/virtual-paginate-controls (:start params ) (:per-page params) (:yodlee-provider-accounts all-yodlee-provider-accounts) )
          :data (grid/virtual-paginate (:start params) (:per-page params) (:yodlee-provider-accounts all-yodlee-provider-accounts)))))

(re-frame/reg-event-fx
 ::data-requested
 [with-user (re-frame/inject-cofx ::inject/sub [::subs/client])]
 (fn [{:keys [user] ::subs/keys [client]} _]
   {:graphql {:token user
              :owns-state {:single ::page}
              :query-obj {:venia/queries [[:yodlee-provider-account-page {:client-id (:id client)}
                                           [[:yodlee-provider-accounts [:id :last-updated :status :detailed-status
                                                                        [:client [:id]]
                                                                        [:accounts [:id :name :number :available-balance]]]]
                                            :count]]]} 
              :on-success [::received]}}))

(re-frame/reg-event-fx
 ::mounted
 (fn [{:keys [db]} _]
   {:dispatch [::data-requested]
    ::forward/register {:id ::yodlee-account-refreshed
                        :events #{::table/refreshed ::table/provider-account-deleted}
                        :event-fn (fn [[_ _]]
                                        [::data-requested])}
    :db (dissoc db ::authentication)}))

(re-frame/reg-event-fx
 ::unmounted
 (fn [_ _]
   {::forward/dispose {:id ::yodlee-account-refreshed}}))


(re-frame/reg-event-fx
 ::authenticate-with-yodlee
 [with-user]
 (fn [{:keys [user]} [_ client]]
   {:http {:token user
           :method :get 
           :headers {"Content-Type" "application/edn"}
           :uri (str "/api/yodlee2/fastlink?client=" client)
           :owns-state {:single ::authenticating}
           :on-success [::authenticated]
           :on-error [::save-error]}}))

(re-frame/reg-event-fx
 ::authenticated
 (fn [{:keys [db]} [_ authentication]]
   {:db (-> db
            (assoc-in [::authentication] authentication))}))

(re-frame/reg-event-db
 ::received
 (fn [db [_ d]]
   (assoc-in db [::yodlee-provider-accounts] (:yodlee-provider-account-page d))))


(defn yodlee-provider-accounts-table []
  [table/table {:page @(re-frame/subscribe [::page])
                :status @(re-frame/subscribe [::status/single ::page])}])


(defn yodlee-link-button []
  [:div
   (let [authentication @(re-frame/subscribe [::authentication])
         status @(re-frame/subscribe [::status/single ::authenticating])
         client-code (:code @(re-frame/subscribe [::subs/client]))]
     (cond (and authentication client-code)
           [:div
            "Authentication successful!"
            [:div#fa-spot]
            [:button.button.is-primary {:on-click (fn []
                                                    (.open (.-fastlink js/window)
                                                           #js {"fastLinkURL" (:url authentication)
                                                                "accessToken" (:token authentication)
                                                                "params" #js { "configName" "Aggregation"}}
                                                           "fa-spot")
                                                    )}
             [:span [:span.icon [:i.fa.fa-external-link]] " Go to yodlee"]]]

           client-code
           [:button.button.is-primary {:disabled (status/disabled-for status)
                                       :class (status/class-for status)
                                       :on-click (dispatch-event [::authenticate-with-yodlee client-code])}
            "Authenticate with Yodlee (" client-code ")"]

           :else
           nil))])

(defn admin-yodlee-provider-accounts-content []
  [:div
   [:h1.title "Yodlee Provider Accounts"]
   [yodlee-provider-accounts-table]
   [yodlee-link-button]])


(defn admin-yodlee-provider-accounts-page []
  (let [user (re-frame/subscribe [::subs/user])]
    (reagent/create-class
      {:component-will-unmount #(re-frame/dispatch [::unmounted])
       :component-did-mount    #(re-frame/dispatch [::mounted])
       :reagent-render         (fn []
                                 (if (not= "manager" (:user/role @user))
                                   [side-bar-layout {:side-bar [company-side-bar {}]
                                                     :main     [admin-yodlee-provider-accounts-content]}]
                                   [:div "Not authorized"]))})))

