(ns auto-ap.db.reminders
  (:require [auto-ap.db.utils :refer [clj->db db->clj get-conn query execute!]]
            [clj-time.core :as time]
            [amazonica.aws.simpleemail :as ses]
            [clojure.java.jdbc :as j]
            [config.core :refer [env]]
            [clj-time.jdbc :as jdbc]
            [clojure.string :as str]
            [honeysql.core :as sql]
            [honeysql.helpers :as helpers]))

(def all-keys #{:id :vendor-id :email :body :subject :sent :scheduled})

(defn insert [row]
  (db->clj (first (j/insert! (get-conn)
                             :reminders
                             (clj->db row)))))

(def base-query (sql/build :select :reminders.*
                           :from :reminders))

(defn get-by-id [id]
  (query (-> base-query
             (helpers/merge-where [:= :id id]))))

(defn update! [id data]
  (println data)
  (-> (sql/build
       :update :reminders
       :set (select-keys data all-keys )
       :where [:= :id id])
      execute!) 
  (get-by-id id))


(defn delete-all []
  (j/delete! (get-conn) :reminders []))

(defn find-future [vendors]
  (map db->clj (j/query (get-conn) (into [(str "SELECT * FROM reminders "
                                               "WHERE vendor_id in ("
                                                    (str/join "," (take (count vendors) (repeat "?")))
                                               ") "
                                               "AND "
                                               "sent is NULL"
                                               ) ]
                                         vendors))))


(defn get-ready []
  (map db->clj (j/query (get-conn)
                        (str
                         " SELECT reminders.*, vendors.name as vendor_name "
                         " FROM reminders INNER join vendors on reminders.vendor_id = vendors.id "
                         " WHERE reminders.sent IS NULL AND reminders.scheduled < NOW()"))))

(defn finish [id]
  (j/update! (get-conn) :reminders {:sent (time/now)} ["id = ?" id] ))



(defn add-sort-by [q sort-by asc]
  (let [sort-by-key (keyword sort-by)]
    (cond (all-keys  sort-by-key)
          (helpers/merge-order-by q [sort-by-key (when-not asc :desc)])

          (= :vendor sort-by-key)
          (-> q
              (helpers/merge-left-join [:vendors :v] [:= :v.id :reminders.vendor-id] )
              (helpers/merge-order-by [:v.name (when-not asc :desc)]))

          :else
          q)))


(defn base-graphql [{:keys [imported company-id]}]
  base-query)

(defn get-graphql [{:keys [start sort-by asc] :as args}]
  (query
   (cond-> (base-graphql args)
     (not (nil? sort-by) ) (add-sort-by sort-by asc)
     true (assoc :limit 20)
     start (assoc :offset start))))

(defn count-graphql [args]
  (:count (first (query
                  (assoc (base-graphql args) :select [:%count.*])))))

(defn template []
  {:subject "Reminder to send invoices"
   :body (str "This is a reminder to please reply with a [format of invoice: pdf/excel]"
              "version of last week's invoices for:"
              "We would greatly appreciate it if you could send that to us by end of day on"
              "Monday.")})

(defn send-emails [reminders]
  (doseq [{:keys [vendor-name id email subject body]} reminders]
    (when email
      (println "Sending email to" email)
      #_(ses/send-email :destination {:to-addresses [email]}
                      :source (:invoice-email env)
                      :message {:subject subject
                                :body {:html (str "<h1>Hello " vendor-name ",</h1><p>" body "</p> <p> - Integreat. </p>")
                                       :text (str "Hello " vendor-name ",\r\n" body "\r\n - Integreat.")}}))
    (finish id)))
