#!/usr/bin/python
# -*- coding: utf-8 -*-
# mutt-hildon: a finger-friendly Hildon front end for the Mutt/msmtp mail setup of the N900.
# List and read INBOX (cached on disk, works offline), reply, write, delete; messages that cannot be sent
# wait in an outbox. "Open Mutt" starts the full terminal client.
# Mail access is in mailcore.py (curl for IMAP, msmtp for SMTP), the cache and outbox in store.py (SQLite),
# the settings come from ~/.muttrc and ~/.mutt-hildon.conf. Python 2.5 + PyGTK + python-hildon (Maemo 5).
import sys
import subprocess
import threading

sys.path.insert(0, "/opt/mutt-hildon")
import gtk
import gobject
import hildon
import mailcore
import store
import contacts

gobject.threads_init()


def banner(widget, text):
    try:
        hildon.hildon_banner_show_information(widget, "", text)
    except Exception:
        sys.stderr.write(text.encode("utf-8") + "\n")


def busy(win, on):
    try:
        hildon.hildon_gtk_window_set_progress_indicator(win, on and 1 or 0)
    except Exception:
        pass


def background(func, done):
    """Run func() in a thread, then done(result, error) in the GTK main loop.
    func must not share SQLite connections with the GUI thread: it opens its own store.Store()."""
    def run():
        res = err = None
        try:
            res = func()
        except mailcore.MailError, e:
            err = unicode(str(e), "utf-8", "replace")
        except Exception, e:
            err = u"%s: %s" % (e.__class__.__name__, e)
        gobject.idle_add(done, res, err)
    t = threading.Thread(target=run)
    t.setDaemon(True)
    t.start()


def menu_button(menu, label, callback):
    b = gtk.Button(label)
    b.connect("clicked", callback)
    menu.append(b)
    return b


def text_view(editable):
    tv = gtk.TextView()
    tv.set_editable(editable)
    tv.set_cursor_visible(editable)
    tv.set_wrap_mode(gtk.WRAP_WORD_CHAR)
    tv.set_left_margin(8)
    tv.set_right_margin(8)
    return tv


class ComposeWin(hildon.StackableWindow):
    """New message or reply. When sending fails the message goes to the outbox instead of being lost."""
    def __init__(self, cfg, on_outbox, to=u"", subject=u"", body=u"", in_reply_to=None):
        hildon.StackableWindow.__init__(self)
        self.cfg = cfg
        self.on_outbox = on_outbox
        self.in_reply_to = in_reply_to
        self.set_title("New message")
        box = gtk.VBox(False, 4)
        self.to = gtk.Entry()
        self.to.set_text(to)
        self.setup_completion()
        self.subject = gtk.Entry()
        self.subject.set_text(subject)
        row = gtk.HBox(False, 6)
        row.pack_start(gtk.Label("To:"), False, False, 4)
        row.pack_start(self.to, True, True, 0)
        box.pack_start(row, False, False, 0)
        row = gtk.HBox(False, 6)
        row.pack_start(gtk.Label("Subject:"), False, False, 4)
        row.pack_start(self.subject, True, True, 0)
        box.pack_start(row, False, False, 0)
        self.body = text_view(True)
        self.body.get_buffer().set_text(body)
        area = hildon.PannableArea()
        area.add(self.body)
        box.pack_start(area, True, True, 0)
        self.add(box)
        menu = hildon.AppMenu()
        menu_button(menu, "Send", self.on_send)
        menu.show_all()
        self.set_app_menu(menu)

    def learn_recipients(self):
        st = store.Store()
        try:
            st.addr_learn(self.to.get_text().decode("utf-8"))
        finally:
            st.close()

    def setup_completion(self):
        """Suggest addresses (phone address book + learned from mail) for the part of the field after the last comma."""
        self.book = contacts.read_addressbook()
        self.suggestions = gtk.ListStore(str, str)
        comp = gtk.EntryCompletion()
        comp.set_model(self.suggestions)
        comp.set_text_column(0)
        comp.set_match_func(lambda _c, _key, _it: True)      # the list is already filtered by suggest()
        comp.set_inline_completion(False)
        comp.connect("match-selected", self.on_suggestion)
        self.to.set_completion(comp)
        self.to.connect("changed", self.on_to_changed)

    def on_to_changed(self, _w):
        head, token = contacts.last_token(self.to.get_text().decode("utf-8"))
        self.suggestions.clear()
        if len(token) < 2:
            return
        st = store.Store()
        try:
            found = contacts.suggest(st, self.book, token)
        finally:
            st.close()
        for display, _addr in found:
            self.suggestions.append([display.encode("utf-8"), _addr.encode("utf-8")])

    def on_suggestion(self, _comp, model, it):
        head, _token = contacts.last_token(self.to.get_text().decode("utf-8"))
        self.to.set_text(head.encode("utf-8") + model.get_value(it, 0) + ", ")
        self.to.set_position(-1)
        return True                                          # we set the text ourselves

    def on_send(self, _w):
        buf = self.body.get_buffer()
        text = buf.get_text(buf.get_start_iter(), buf.get_end_iter())
        to = self.to.get_text().strip()
        subject = self.subject.get_text()
        if not to:
            banner(self, u"Enter a recipient")
            return
        if not mailcore.recipients(to):
            banner(self, u"Invalid recipient")
            return
        busy(self, True)

        def done(_res, err):
            busy(self, False)
            if err:
                # Keep the message: it is sent by Refresh when the network works.
                st = store.Store()
                try:
                    st.outbox_add(to, subject, text, self.in_reply_to, err)
                finally:
                    st.close()
                banner(self, u"Not sent (%s). Saved to the outbox, Refresh tries again." % err[:80])
                self.on_outbox()
            else:
                banner(self, u"Message sent")
                self.learn_recipients()
            self.destroy()
            return False
        background(lambda: mailcore.send(self.cfg, to, subject, text, self.in_reply_to), done)


class OutboxWin(hildon.StackableWindow):
    """Unsent messages. Tap one to edit it (it leaves the outbox and opens in the composer)."""
    def __init__(self, cfg, on_outbox):
        hildon.StackableWindow.__init__(self)
        self.cfg = cfg
        self.on_outbox = on_outbox
        self.set_title("Outbox")
        self.items = []
        self.store = gtk.ListStore(str, int)
        tree = gtk.TreeView(self.store)
        tree.set_headers_visible(False)
        cell = gtk.CellRendererText()
        cell.set_property("ellipsize", 3)
        tree.append_column(gtk.TreeViewColumn("Unsent", cell, text=0))
        tree.connect("row-activated", self.on_activated)
        area = hildon.PannableArea()
        area.add(tree)
        self.add(area)
        menu = hildon.AppMenu()
        menu_button(menu, "Discard all", self.on_discard_all)
        menu.show_all()
        self.set_app_menu(menu)
        self.fill()

    def fill(self):
        st = store.Store()
        try:
            self.items = st.outbox_list()
        finally:
            st.close()
        self.store.clear()
        for m in self.items:
            line = u"%s | %s\n%s" % (m["to"], m["subject"], m["error"] or u"")
            self.store.append((line.encode("utf-8"), m["id"]))

    def on_activated(self, _tree, path, _col):
        oid = self.store[path][1]
        for m in self.items:
            if m["id"] == oid:
                st = store.Store()
                try:
                    st.outbox_remove(oid)
                finally:
                    st.close()
                self.on_outbox()
                ComposeWin(self.cfg, self.on_outbox, m["to"], m["subject"], m["body"], m["in_reply_to"]).show_all()
                self.destroy()
                return

    def on_discard_all(self, _w):
        dlg = gtk.MessageDialog(self, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION, gtk.BUTTONS_YES_NO,
                                "Discard all unsent messages?")
        answer = dlg.run()
        dlg.destroy()
        if answer == gtk.RESPONSE_YES:
            st = store.Store()
            try:
                for m in self.items:
                    st.outbox_remove(m["id"])
            finally:
                st.close()
            self.on_outbox()
            self.destroy()


class MessageWin(hildon.StackableWindow):
    def __init__(self, cfg, row, settings, on_changed, on_outbox):
        hildon.StackableWindow.__init__(self)
        self.cfg = cfg
        self.row = row          # dict from the cache: idx, message_id, subject, ...
        self.settings = settings
        self.on_changed = on_changed
        self.on_outbox = on_outbox
        self.msg = None
        self.set_title(row["subject"][:40])
        self.head = gtk.Label("Loading...")
        self.head.set_alignment(0, 0)
        self.head.set_line_wrap(True)
        self.view = text_view(False)
        box = gtk.VBox(False, 4)
        box.pack_start(self.head, False, False, 4)
        area = hildon.PannableArea()
        area.add(self.view)
        box.pack_start(area, True, True, 0)
        self.add(box)
        menu = hildon.AppMenu()
        menu_button(menu, "Reply", self.on_reply)
        menu_button(menu, "Delete", self.on_delete)
        menu.show_all()
        self.set_app_menu(menu)
        self.load()

    def load(self):
        """From the cache at once; otherwise download and keep it for next time."""
        st = store.Store()
        try:
            cached = st.get_body(self.row["message_id"])
        finally:
            st.close()
        if cached:
            self.loaded(cached, None)
            return
        busy(self, True)
        mid, idx, cfg = self.row["message_id"], self.row["idx"], self.cfg

        def fetch():
            msg = mailcore.parse_message(mailcore.fetch_raw(cfg, idx))
            if (msg.get("message_id") or "").strip() != mid:
                raise mailcore.MailError("The mailbox changed, press Refresh in the list")
            s = store.Store()
            try:
                s.set_body(mid, msg)
            finally:
                s.close()
            return msg
        background(fetch, self.loaded)

    def loaded(self, msg, err):
        busy(self, False)
        if err:
            self.head.set_text(err)
            return False
        self.msg = msg
        head = u"From: %s\nDate: %s\nSubject: %s" % (msg["from"], msg["date"], msg["subject"])
        if msg["attachments"]:
            head += u"\nAttachments (not shown): " + u", ".join(msg["attachments"])
        self.head.set_text(head)
        self.view.get_buffer().set_text(msg["body"])
        return False

    def on_delete(self, _w):
        if self.settings["confirm_delete"]:
            dlg = gtk.MessageDialog(self, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION, gtk.BUTTONS_YES_NO,
                                    "Delete this message?")
            answer = dlg.run()
            dlg.destroy()
            if answer != gtk.RESPONSE_YES:
                return
        busy(self, True)
        mid, idx, cfg = self.row["message_id"], self.row["idx"], self.cfg
        to_trash = bool(self.settings["delete_to_trash"])

        def done(_res, err):
            busy(self, False)
            if err:
                banner(self, u"Delete failed: " + err)
            else:
                self.on_changed()
                self.destroy()
            return False

        def work():
            mailcore.delete(cfg, idx, mid, to_trash)
            s = store.Store()
            try:
                s.delete_message(mid)
            finally:
                s.close()
        background(work, done)

    def on_reply(self, _w):
        if not self.msg:
            return
        to, subject, body = mailcore.reply_draft(self.msg)
        ComposeWin(self.cfg, self.on_outbox, to, subject, body, self.msg.get("message_id")).show_all()


class MainWin(hildon.StackableWindow):
    def __init__(self, cfg):
        hildon.StackableWindow.__init__(self)
        self.cfg = cfg
        self.settings = mailcore.load_settings()
        self.loading = False
        self.timer = None
        self.shown = self.settings["page_size"]   # how many cached messages the list shows
        self.rows = []
        self.store = gtk.ListStore(str)
        try:
            tree = hildon.gtk_tree_view_new_with_model(hildon.HILDON_UI_MODE_NORMAL, self.store)
        except AttributeError:
            tree = gtk.TreeView(self.store)
        tree.set_headers_visible(False)
        cell = gtk.CellRendererText()
        cell.set_property("ellipsize", 3)  # pango.ELLIPSIZE_END
        tree.append_column(gtk.TreeViewColumn("Mail", cell, markup=0))
        tree.connect("row-activated", self.on_activated)
        area = hildon.PannableArea()
        area.add(tree)
        self.add(area)
        menu = hildon.AppMenu()
        menu_button(menu, "New message", self.on_new)
        menu_button(menu, "Refresh", self.on_refresh)
        menu_button(menu, "Older messages", self.on_older)
        menu_button(menu, "Outbox", self.on_outbox_window)
        menu_button(menu, "Settings", self.on_settings)
        menu_button(menu, "Open Mutt", self.on_mutt)
        menu.show_all()
        self.set_app_menu(menu)
        self.render()                 # the cache is shown at once, before any network traffic
        self.connect("show", self.on_show)
        self.restart_timer()

    def on_show(self, _w):
        self.on_refresh(None)

    # ---- list from the cache ----
    def render(self):
        st = store.Store()
        try:
            self.rows = st.page(self.shown)
            unsent = st.outbox_count()
        finally:
            st.close()
        esc = lambda s: s.replace(u"&", u"&amp;").replace(u"<", u"&lt;").replace(u">", u"&gt;")
        self.store.clear()
        for h in self.rows:
            row = u"<b>%s</b>  <small>%s</small>\n%s" % (esc(h["from"]), esc(h["date"]), esc(h["subject"]))
            self.store.append((row.encode("utf-8"),))
        self.set_title(unsent and ("Mail (%d unsent)" % unsent) or "Mail")

    def outbox_changed(self):
        self.render()

    # ---- network ----
    def restart_timer(self):
        """Automatic refresh every `refresh_minutes` (0 = off); skipped while another load is running."""
        if self.timer:
            gobject.source_remove(self.timer)
            self.timer = None
        minutes = self.settings["refresh_minutes"]
        if minutes > 0:
            self.timer = gobject.timeout_add_seconds(minutes * 60, self.on_timer)

    def on_timer(self):
        if not self.loading:
            self.refresh(False)     # the timer only reads; sending the outbox is done by the Refresh button
        return True

    def on_refresh(self, _w):
        self.refresh(True)

    def refresh(self, flush):
        if self.loading:
            return
        self.loading = True
        busy(self, True)
        cfg, size, keep = self.cfg, self.settings["page_size"], self.settings["cache_messages"]

        def work():
            res = {"sent": 0, "left": 0, "send_error": None}
            s = store.Store()
            try:
                if flush:
                    res["sent"], res["left"], res["send_error"] = store.flush_outbox(cfg, s, mailcore.send)
                items = mailcore.list_inbox(cfg, size)
                s.upsert_headers(items)
                s.reconcile(items)
                s.prune(keep)
            finally:
                s.close()
            return res
        background(work, self.refreshed)

    def refreshed(self, res, err):
        busy(self, False)
        self.loading = False
        self.render()
        if res:
            if res["sent"]:
                banner(self, u"%d unsent message(s) sent" % res["sent"])
            elif res["left"] and res["send_error"]:
                banner(self, u"%d message(s) still unsent: %s" % (res["left"], res["send_error"][:80]))
        if err:
            banner(self, u"Offline or error, showing cached mail: " + err[:80])
        return False

    def on_older(self, _w):
        """Show the next page; from the cache if it has it, otherwise download it first."""
        before = self.shown
        self.shown += self.settings["page_size"]
        self.render()
        if len(self.rows) > before or self.loading or not self.rows:
            return
        oldest = min([r["idx"] for r in self.rows])
        if oldest <= 1:
            banner(self, u"No older messages")
            return
        self.loading = True
        busy(self, True)
        cfg, size = self.cfg, self.settings["page_size"]

        def work():
            items = mailcore.list_inbox(cfg, size, before=oldest)
            s = store.Store()
            try:
                s.upsert_headers(items)
            finally:
                s.close()
            return len(items)

        def done(n, err):
            self.loading = False
            busy(self, False)
            self.render()
            if err:
                banner(self, u"Cannot load older mail: " + err[:80])
            return False
        background(work, done)

    # ---- actions ----
    def on_activated(self, _tree, path, _col):
        row = self.rows[path[0]]
        MessageWin(self.cfg, row, self.settings, lambda: self.on_refresh(None), self.outbox_changed).show_all()

    def on_new(self, _w):
        ComposeWin(self.cfg, self.outbox_changed).show_all()

    def on_outbox_window(self, _w):
        OutboxWin(self.cfg, self.outbox_changed).show_all()

    def on_mutt(self, _w):
        subprocess.Popen(["/usr/bin/osso-xterm", "-e", "/usr/bin/mutt"])

    def on_settings(self, _w):
        dlg = gtk.Dialog("Settings", self, gtk.DIALOG_MODAL, ("Save", gtk.RESPONSE_OK))
        rows = []
        for key, label in (("refresh_minutes", "Refresh every (minutes, 0 = off)"),
                           ("page_size", "Messages per page"),
                           ("cache_messages", "Messages kept on disk")):
            lo, hi = mailcore.SETTING_LIMITS[key]
            spin = gtk.SpinButton(gtk.Adjustment(self.settings[key], lo, hi, 1, 10, 0))
            row = gtk.HBox(False, 8)
            row.pack_start(gtk.Label(label), False, False, 8)
            row.pack_end(spin, False, False, 8)
            dlg.vbox.pack_start(row, False, False, 4)
            rows.append((key, spin))
        checks = []
        for key, label in (("confirm_delete", "Ask before deleting"),
                           ("delete_to_trash", "Move deleted messages to the trash folder")):
            chk = gtk.CheckButton(label)
            chk.set_active(bool(self.settings[key]))
            dlg.vbox.pack_start(chk, False, False, 4)
            checks.append((key, chk))
        dlg.show_all()
        if dlg.run() == gtk.RESPONSE_OK:
            for key, spin in rows:
                self.settings[key] = int(spin.get_value())
            for key, chk in checks:
                self.settings[key] = int(chk.get_active())
            try:
                mailcore.save_settings(self.settings)
            except IOError, e:
                banner(self, u"Cannot save settings: %s" % e)
            self.restart_timer()
        dlg.destroy()


def main():
    err = None
    try:
        cfg = mailcore.load_config()
    except mailcore.MailError, e:
        cfg = None
        err = str(e)
    program = hildon.Program.get_instance()
    if cfg is None:
        win = hildon.StackableWindow()
        win.add(gtk.Label(err))
    else:
        win = MainWin(cfg)
    program.add_window(win)
    win.connect("destroy", gtk.main_quit)
    win.show_all()
    gtk.main()

if __name__ == "__main__":
    main()
