(use goo)

(use util/net/mail/cclient)
(use util/net/mail/cclientx.swig)

(use util/io/text/formatout)

;; (use util/net/mail/cclient-examples/imap)

(df read-nonempty-string ()
  (def s (gets in))
  (if (= s "")
      (read-nonempty-string)
      s)
  )

;;(dv mailbox "{catgufu.ai.mit.edu/debug/user=sombrero}INBOX")
(dv mailbox "{catgufu.ai.mit.edu/imap/ssl/novalidate-cert}INBOX")

(df callback-login (mailbox trial)
  (post "Enter your username you bastard!:\n")
  (def username (read-nonempty-string))
  (post "And now the password!:\n")
  (def password (read-nonempty-string))
  (tup username password)
  )

(df callback-list (stream delimiter name attributes)
  (post "Mailbox: %=\n" name)
  )

;; Register our callbacks
(set_cclient_callback CCALLBACK_LOGIN callback-login)
(set_cclient_callback CCALLBACK_LIST callback-list)

(dv my-stream (open-mail-stream mailbox))
(dv my-box (make-client-mailbox my-stream))


(post "There are %d messages\n" (num-msgs my-box))

(dv cur-msg (- (num-msgs my-box) 1))

(df scan (opt|...)
  (rep loop ((i 1))
    (when (< i (num-msgs my-box))
      (def my-env (envelope (get-msg my-stream my-box i)))
      (post "%d: %s\n" i (subject my-env))
      (loop (+ i 1))
      )
    )
  )

(dm to-str (addr|<cclient-address> => <str>)
  (cat (persons-name addr) " <" (mailbox-name addr) "@" (host-name addr) ">")
  )

(df show (opt|...)
  (when (not (empty? opt))
    (set cur-msg (1st opt))
    )
  (def da-msg (get-msg my-box cur-msg))
  (def env (envelope da-msg))
  (msg-labelled-list out "From:" (from-addrs env))
  (msg-labelled-list out "To:" (to-addrs env))
  (msg-labelled-list out "Cc:" (cc-addrs env))
  (msg-labelled-list out "Bcc:" (bcc-addrs env))
  (msg out "Date: %s\n" (message-date env))
  (msg out "Subject: %s\n" (subject env))
  (msg out "-----------------\n")
  (msg out "%s\n" (get-body-text da-msg))
  )

(df next ()
  (if (< (+ cur-msg 1) (num-msgs my-box))
      (seq
        (incf cur-msg)
        (show)
        )
      (seq
        (post "We're on the last message already!\n")
        )
      )
  )

(df prev ()
  (if (> cur-msg 1)
      (seq
        (decf cur-msg)
        (show)
        )
      (seq
        (post "We're on the first message already!\n")
        )
      )
  )

(df rmm ()
  (delete-message my-stream my-box cur-msg)
  (decf cur-msg)
  (next)
  )

(export
  scan
  show
  next
  prev
  rmm
  )