(ns auto-ap.views.pages.company.other
  (:require
   [auto-ap.subs :as subs]
   [auto-ap.views.utils :refer [dispatch-event with-user]]
   [auto-ap.views.components.buttons :refer [fa-icon]]
   [auto-ap.views.components.layouts :refer [side-bar-layout]]
   [auto-ap.shared-views.company.sidebar :refer [company-side-bar]]
   [goog.crypt.base64 :as b64]
   [re-frame.core :as re-frame]
   [reagent.core :as reagent]
   [vimsical.re-frame.cofx.inject :as inject]
   [auto-ap.status :as status]
   [clojure.string :as str]))

(re-frame/reg-event-fx
  ::ready
  (fn [{:keys [db] } [_ result]]
    {:db (assoc db ::export-result result)}))

(re-frame/reg-sub
  ::export-result
  (fn [db]
    (::export-result db)))

(re-frame/reg-event-fx
  ::export-vendors
  [(re-frame/inject-cofx ::inject/sub [::subs/client]) with-user]
  (fn [{:keys [db user] ::subs/keys [client]}]
    {:http {:token      user
            :method     :get 
            :headers    {"Content-Type" "application/edn"}
            :uri        (str "/api/vendors/company/export?client=" (:code client))
            :owns-state {:single ::export-vendors}
            :on-success [::ready]}}))

(re-frame/reg-event-fx
  ::unmounted
  (fn [{:keys [db]} _]
    {:db (dissoc db ::export-result)}))

(defn company-other-content []
  (let [client @(re-frame/subscribe [::subs/client])
        state  @(re-frame/subscribe [::status/single ::export-vendors])
        export-result @(re-frame/subscribe [::export-result])]
    (if client 
      [:div
       [:h1.title "Other"]
       [status/status-notification [::status/single ::export-vendors]]
       

       [fa-icon {:icon "fa-external-link"
                 :class (into (status/class-for state) ["is-primary" ])
                 :disabled (status/disabled-for state)
                 :event [::export-vendors]
                 }
        [:div 
         (str " Export " (:name client) " Vendors")
         ]]
       (when export-result
         [:<> 
          [:div 
           "Ready! Click "
           [:a {:href     (str "data:attachment/csv;base64," (b64/encodeString export-result))
                :target   "_blank"
                :download (str "vendors-" (:code client) ".csv")}
            "here"]
           " to download"]])
       ]
      [:div "Please select a company."])))


(defn company-other-page []
  (reagent/create-class
    {:reagent-render         (fn []
                               [side-bar-layout {:side-bar [company-side-bar {}]
                                                 :main     [company-other-content]}])
     :component-will-unmount #(re-frame/dispatch [::unmounted])}))

