 (ns appengine-magic.services.mail
   (:refer-clojure :exclude (send))
+  (:use [appengine-magic.utils :only [record]])
   (:import [com.google.appengine.api.mail MailServiceFactory
             MailService$Message MailService$Attachment]))
 



(defrecord MailMessage [from to subject text-body html-body
                        reply-to cc bcc attachments])


(defn make-attachment [filename data]
  (MailService$Attachment. filename data))


(defn make-mail-message [& {:keys [from to subject text-body html-body
                                   reply-to cc bcc attachments]
                            :or {text-body "", html-body "", cc [], bcc [], attachments []}}]
  ;; normalize and error-check
  (let [from (if-not (nil? from)
                 from


(defn send-to-admins [^MailMessage msg]
  (.sendToAdmins (get-mail-service) (make-mail-service-message msg)))


(defn parse-message [request]
  (let [session (javax.mail.Session/getDefaultInstance (java.util.Properties.) nil)
        raw-msg (javax.mail.internet.MimeMessage. session (.getInputStream (:request request)))
        from (first (map #(.toString %) (.getFrom raw-msg)))
        subject (.getSubject raw-msg)
        sent-date (.getSentDate raw-msg)
        received-date (.getReceivedDate raw-msg)
        to (map #(.toString %) (.getRecipients raw-msg javax.mail.Message$RecipientType/TO))
        cc (map #(.toString %) (.getRecipients raw-msg javax.mail.Message$RecipientType/CC))
        reply-to (first (map #(.toString %) (.getReplyTo raw-msg)))
        message-id (.getMessageID raw-msg)]
    (record MailMessage
            :from from :to to :subject subject
            :reply-to reply-to :cc cc)))
