(ns auto-ap.background.mail
  (:require [amazonica.aws.s3 :as s3]
            [amazonica.aws.sqs :as sqs]
            [auto-ap.db.companies :as companies]
            [auto-ap.db.vendors :as vendors]
            [auto-ap.db.invoices :as invoices]
            [auto-ap.parse :as parse]
            [clojure-mail.message :as message]
            [clojure.data.json :as json]
            [clojure.java.io :as io]
            [config.core :refer [env]])
  (:import (java.util Properties UUID)
           (javax.mail Session)
           (javax.mail.internet MimeMessage)))


(defn process-sqs []
  (try
    (println "Fetching messages from sqs...")
    (let [companies (companies/get-all)
          vendors (vendors/get-all)]
      (doseq [message (:messages (sqs/receive-message {:queue-url (:invoice-import-queue-url env)
                                                       :wait-time-seconds 5
                                                       :max-number-of-messages 10
                                                       #_#_:attribute-names ["All"]}))]
        (let [message-body (json/read-str (:body message)
                                          :key-fn keyword)]
          (doseq [r (:Records message-body)] 
            (println "Processing record " r)
            (let [props (Session/getDefaultInstance (Properties.))
                  message-stream (-> (s3/get-object {:key (-> r :s3 :object :key)
                                                     :bucket-name (-> r :s3 :bucket :name)})
                                     :input-stream)
                  mail (message/read-message (MimeMessage. props message-stream))]
              (doseq [pdf-stream (->> (-> mail :body)
                                      (filter :content-type)
                                      (filter #(re-find #"application/pdf" (:content-type %)) ))]
                (let [filename (str "/tmp/" (UUID/randomUUID) ".pdf")]
                  (io/copy (:body pdf-stream) (io/file filename))
                  (invoices/import (parse/parse-file filename filename) companies)
                  (io/delete-file filename))))))
        (sqs/delete-message (assoc message :queue-url (:invoice-import-queue-url env) ))))
    (catch Exception e
      (println e))))

(defn always-process-sqs []
  (while (not (Thread/interrupted))
    (process-sqs)))
